LP1702911: Correct Barcode State in Add Item
[working/Evergreen.git] / Open-ILS / web / js / ui / default / staff / cat / volcopy / app.js
1 /**
2  * Vol/Copy Editor
3  */
4
5 angular.module('egVolCopy',
6     ['ngRoute', 'ui.bootstrap', 'egCoreMod', 'egUiMod', 'egGridMod'])
7
8 .filter('boolText', function(){
9     return function (v) {
10         return v == 't';
11     }
12 })
13
14 .config(['ngToastProvider', function(ngToastProvider) {
15   ngToastProvider.configure({
16     verticalPosition: 'bottom',
17     animation: 'fade'
18   });
19 }])
20
21 .config(function($routeProvider, $locationProvider, $compileProvider) {
22     $locationProvider.html5Mode(true);
23     $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|blob):/); // grid export
24
25     var resolver = {
26         delay : ['egStartup', function(egStartup) { return egStartup.go(); }]
27     };
28
29     $routeProvider.when('/cat/volcopy/edit_templates', {
30         templateUrl: './cat/volcopy/t_view',
31         controller: 'EditCtrl',
32         resolve : resolver
33     });
34
35     $routeProvider.when('/cat/volcopy/:dataKey', {
36         templateUrl: './cat/volcopy/t_view',
37         controller: 'EditCtrl',
38         resolve : resolver
39     });
40
41     $routeProvider.when('/cat/volcopy/:dataKey/:mode', {
42         templateUrl: './cat/volcopy/t_view',
43         controller: 'EditCtrl',
44         resolve : resolver
45     });
46 })
47
48 .factory('itemSvc', 
49        ['egCore','$q',
50 function(egCore , $q) {
51
52     var service = {
53         currently_generating : false,
54         auto_gen_barcode : false,
55         barcode_checkdigit : false,
56         new_cp_id : 0,
57         new_cn_id : 0,
58         tree : {}, // holds lib->cn->copy hash stack
59         copies : [] // raw copy list
60     };
61
62     service.nextBarcode = function(bc) {
63         service.currently_generating = true;
64         return egCore.net.request(
65             'open-ils.cat',
66             'open-ils.cat.item.barcode.autogen',
67             egCore.auth.token(),
68             bc, 1, { checkdigit: service.barcode_checkdigit }
69         ).then(function(resp) { // get_barcodes
70             var evt = egCore.evt.parse(resp);
71             if (!evt) return resp[0];
72             return '';
73         });
74     };
75
76     service.checkBarcode = function(bc) {
77         if (!service.barcode_checkdigit) return true;
78         if (bc != Number(bc)) return false;
79         bc = bc.toString();
80         // "16.00" == Number("16.00"), but the . is bad.
81         // Throw out any barcode that isn't just digits
82         if (bc.search(/\D/) != -1) return false;
83         var last_digit = bc.substr(bc.length-1);
84         var stripped_barcode = bc.substr(0,bc.length-1);
85         return service.barcodeCheckdigit(stripped_barcode).toString() == last_digit;
86     };
87
88     service.barcodeCheckdigit = function(bc) {
89         var reverse_barcode = bc.toString().split('').reverse();
90         var check_sum = 0; var multiplier = 2;
91         for (var i = 0; i < reverse_barcode.length; i++) {
92             var digit = reverse_barcode[i];
93             var product = digit * multiplier; product = product.toString();
94             var temp_sum = 0;
95             for (var j = 0; j < product.length; j++) {
96                 temp_sum += Number( product[j] );
97             }
98             check_sum += Number( temp_sum );
99             multiplier = ( multiplier == 2 ? 1 : 2 );
100         }
101         check_sum = check_sum.toString();
102         var next_multiple_of_10 = (check_sum.match(/(\d*)\d$/)[1] * 10) + 10;
103         var check_digit = next_multiple_of_10 - Number(check_sum); if (check_digit == 10) check_digit = 0;
104         return check_digit;
105     };
106
107     // returns a promise resolved with the list of circ mods
108     service.get_classifications = function() {
109         if (egCore.env.acnc)
110             return $q.when(egCore.env.acnc.list);
111
112         return egCore.pcrud.retrieveAll('acnc', null, {atomic : true})
113         .then(function(list) {
114             egCore.env.absorbList(list, 'acnc');
115             return list;
116         });
117     };
118
119     service.get_prefixes = function(org) {
120         return egCore.pcrud.search('acnp',
121             {owning_lib : egCore.org.fullPath(org, true)},
122             {order_by : { acnp : 'label_sortkey' }}, {atomic : true}
123         );
124
125     };
126
127     service.get_statcats = function(orgs) {
128         return egCore.pcrud.search('asc',
129             {owner : orgs},
130             { flesh : 1,
131               flesh_fields : {
132                 asc : ['owner','entries']
133               }
134             },
135             { atomic : true }
136         );
137     };
138
139     service.get_locations = function(orgs) {
140         return egCore.pcrud.search('acpl',
141             {owning_lib : orgs},
142             {order_by : { acpl : 'name' }}, {atomic : true}
143         );
144     };
145
146     service.get_suffixes = function(org) {
147         return egCore.pcrud.search('acns',
148             {owning_lib : egCore.org.fullPath(org, true)},
149             {order_by : { acns : 'label_sortkey' }}, {atomic : true}
150         );
151
152     };
153
154     service.get_magic_statuses = function() {
155         /* TODO: make these more configurable per lp1616170 */
156         return $q.when([
157              1  /* Checked out */
158             ,3  /* Lost */
159             ,6  /* In transit */
160             ,8  /* On holds shelf */
161             ,16 /* Long overdue */
162             ,18 /* Canceled Transit */
163         ]);
164     }
165
166     service.get_statuses = function() {
167         if (egCore.env.ccs)
168             return $q.when(egCore.env.ccs.list);
169
170         return egCore.pcrud.retrieveAll('ccs', {order_by : { ccs : 'name' }}, {atomic : true}).then(
171             function(list) {
172                 egCore.env.absorbList(list, 'ccs');
173                 return list;
174             }
175         );
176
177     };
178
179     service.get_circ_mods = function() {
180         if (egCore.env.ccm)
181             return $q.when(egCore.env.ccm.list);
182
183         return egCore.pcrud.retrieveAll('ccm', {}, {atomic : true}).then(
184             function(list) {
185                 egCore.env.absorbList(list, 'ccm');
186                 return list;
187             }
188         );
189
190     };
191
192     service.get_circ_types = function() {
193         if (egCore.env.citm)
194             return $q.when(egCore.env.citm.list);
195
196         return egCore.pcrud.retrieveAll('citm', {}, {atomic : true}).then(
197             function(list) {
198                 egCore.env.absorbList(list, 'citm');
199                 return list;
200             }
201         );
202
203     };
204
205     service.get_age_protects = function() {
206         if (egCore.env.crahp)
207             return $q.when(egCore.env.crahp.list);
208
209         return egCore.pcrud.retrieveAll('crahp', {}, {atomic : true}).then(
210             function(list) {
211                 egCore.env.absorbList(list, 'crahp');
212                 return list;
213             }
214         );
215
216     };
217
218     service.get_floating_groups = function() {
219         if (egCore.env.cfg)
220             return $q.when(egCore.env.cfg.list);
221
222         return egCore.pcrud.retrieveAll('cfg', {}, {atomic : true}).then(
223             function(list) {
224                 egCore.env.absorbList(list, 'cfg');
225                 return list;
226             }
227         );
228
229     };
230
231     service.bmp_parts = {};
232     service.get_parts = function(rec) {
233         if (service.bmp_parts[rec])
234             return $q.when(service.bmp_parts[rec]);
235
236         return egCore.pcrud.search('bmp',
237             {record : rec, deleted : 'f'},
238             null, {atomic : true}
239         ).then(function(list) {
240             service.bmp_parts[rec] = list;
241             return list;
242         });
243
244     };
245
246     service.flesh = {   
247         flesh : 3, 
248         flesh_fields : {
249             acp : ['call_number','parts','stat_cat_entries', 'notes', 'tags'],
250             acn : ['label_class','prefix','suffix'],
251             acptcm : ['tag']
252         }
253     }
254
255     service.addCopy = function (cp) {
256
257         if (!cp.parts()) cp.parts([]); // just in case...
258
259         var lib = cp.call_number().owning_lib();
260         var cn = cp.call_number().id();
261
262         if (!service.tree[lib]) service.tree[lib] = {};
263         if (!service.tree[lib][cn]) service.tree[lib][cn] = [];
264
265         service.tree[lib][cn].push(cp);
266         service.copies.push(cp);
267     }
268
269     service.checkDuplicateBarcode = function(bc, id) {
270         var final = false;
271         return egCore.pcrud.search('acp', { deleted : 'f', 'barcode' : bc, id : { '!=' : id } })
272             .then(
273                 function () { return final },
274                 function () { return final },
275                 function () { final = true; }
276             );
277     }
278
279     service.fetchIds = function(idList) {
280         service.tree = {}; // clear the tree on fetch
281         service.copies = []; // clear the copy list on fetch
282         return egCore.pcrud.search('acp', { 'id' : idList }, service.flesh).then(null,null,
283             function(copy) {
284                 service.addCopy(copy);
285             }
286         );
287     }
288
289     // create a new acp object with default values
290     // (both hard-coded and coming from OU settings)
291     service.generateNewCopy = function(callNumber, owningLib, isFastAdd, isNew) {
292         var cp = new egCore.idl.acp();
293         cp.id( --service.new_cp_id );
294         if (isNew) {
295             cp.isnew( true );
296         }
297         cp.circ_lib( owningLib );
298         cp.call_number( callNumber );
299         cp.deposit(0);
300         cp.price(0);
301         cp.deposit_amount(0);
302         cp.fine_level(2); // Normal
303         cp.loan_duration(2); // Normal
304         cp.location(1); // Stacks
305         cp.circulate('t');
306         cp.holdable('t');
307         cp.opac_visible('t');
308         cp.ref('f');
309         cp.mint_condition('t');
310         cp.empty_barcode = true;
311
312         var status_setting = isFastAdd ?
313             'cat.default_copy_status_fast' :
314             'cat.default_copy_status_normal';
315         egCore.org.settings(
316             [status_setting],
317             owningLib
318         ).then(function(set) {
319             var default_ccs = parseInt(set[status_setting]);
320             if (isNaN(default_ccs))
321                 default_ccs = (isFastAdd ? 0 : 5); // 0 is Available, 5 is In Process
322             cp.status(default_ccs);
323         });
324
325         return cp;
326     }
327
328     return service;
329 }])
330
331 .directive("egVolCopyEdit", function () {
332     return {
333         restrict: 'E',
334         replace: true,
335         template:
336             '<div class="row">'+
337                 '<div class="col-xs-5" ng-class="{'+"'has-error'"+':barcode_has_error}">'+
338                     '<input id="{{callNumber.id()}}_{{copy.id()}}"'+
339                     ' eg-enter="nextBarcode(copy.id())" class="form-control"'+
340                     ' type="text" ng-model="barcode" ng-change="updateBarcode()"/>'+
341                     '<div class="label label-danger" ng-if="duplicate_barcode">{{duplicate_barcode_string}}</div>'+
342                     '<div class="label label-danger" ng-if="empty_barcode">{{empty_barcode_string}}</div>'+
343                 '</div>'+
344                 '<div class="col-xs-3"><input class="form-control" type="number" min="1" ng-model="copy_number" ng-change="updateCopyNo()"/></div>'+
345                 '<div class="col-xs-4"><eg-basic-combo-box eg-disabled="record == 0" list="parts" selected="part"></eg-basic-combo-box></div>'+
346             '</div>',
347
348         scope: { focusNext: "=", copy: "=", callNumber: "=", index: "@", record: "@" },
349         controller : ['$scope','itemSvc','egCore',
350             function ( $scope , itemSvc , egCore ) {
351                 $scope.new_part_id = 0;
352                 $scope.barcode_has_error = false;
353                 $scope.duplicate_barcode = false;
354                 $scope.empty_barcode = false;
355                 $scope.duplicate_barcode_string = window.duplicate_barcode_string;
356                 $scope.empty_barcode_string = window.empty_barcode_string;
357
358                 if (!$scope.copy.barcode()) $scope.copy.empty_barcode = true;
359
360                 $scope.nextBarcode = function (i) {
361                     $scope.focusNext(i, $scope.barcode);
362                 }
363
364                 $scope.updateBarcode = function () {
365                     if ($scope.barcode != '') {
366                         $scope.copy.empty_barcode = $scope.empty_barcode = false;
367                         $scope.barcode_has_error = !Boolean(itemSvc.checkBarcode($scope.barcode));
368                         itemSvc.checkDuplicateBarcode($scope.barcode, $scope.copy.id())
369                             .then(function (state) { $scope.copy.duplicate_barcode = $scope.duplicate_barcode = state });
370                     } else {
371                         $scope.copy.empty_barcode = $scope.empty_barcode = true;
372                     }
373                         
374                     $scope.copy.barcode($scope.barcode);
375                     $scope.copy.ischanged(1);
376                     if (itemSvc.currently_generating)
377                         $scope.focusNext($scope.copy.id(), $scope.barcode);
378                 };
379
380                 $scope.updateCopyNo = function () { $scope.copy.copy_number($scope.copy_number); $scope.copy.ischanged(1); };
381                 $scope.updatePart = function () {
382                     if ($scope.part) {
383                         var p = $scope.part_list.filter(function (x) {
384                             return x.label() == $scope.part
385                         });
386                         if (p.length > 0) { // preexisting part
387                             $scope.copy.parts(p)
388                         } else { // create one...
389                             var part = new egCore.idl.bmp();
390                             part.id( --$scope.new_part_id );
391                             part.isnew( true );
392                             part.label( $scope.part );
393                             part.record( $scope.callNumber.record() );
394                             $scope.copy.parts([part]);
395                             $scope.copy.ischanged(1);
396                         }
397                     } else {
398                         $scope.copy.parts([]);
399                     }
400                     $scope.copy.ischanged(1);
401                 }
402                 $scope.$watch('part', $scope.updatePart);
403
404                 $scope.barcode = $scope.copy.barcode();
405                 $scope.copy_number = $scope.copy.copy_number();
406
407                 if ($scope.copy.parts()) {
408                     $scope.part = $scope.copy.parts()[0];
409                     if ($scope.part) $scope.part = $scope.part.label();
410                 };
411
412                 $scope.parts = [];
413                 $scope.part_list = [];
414
415                 itemSvc.get_parts($scope.callNumber.record()).then(function(list){
416                     $scope.part_list = list;
417                     angular.forEach(list, function(p){ $scope.parts.push(p.label()) });
418                     $scope.parts = angular.copy($scope.parts);
419                 });
420
421             }
422         ]
423
424     }
425 })
426
427 .directive("egVolRow", function () {
428     return {
429         restrict: 'E',
430         replace: true,
431         transclude: true,
432         template:
433             '<div class="row">'+
434                 '<div class="col-xs-2">'+
435                     '<select ng-disabled="record == 0" class="form-control" ng-model="classification" ng-change="updateClassification()" ng-options="cl.name() for cl in classification_list"/>'+
436                 '</div>'+
437                 '<div class="col-xs-1">'+
438                     '<select ng-disabled="record == 0" class="form-control" ng-model="prefix" ng-change="updatePrefix()" ng-options="p.label() for p in prefix_list"/>'+
439                 '</div>'+
440                 '<div class="col-xs-2">'+
441                     '<input ng-disabled="record == 0" class="form-control" type="text" ng-change="updateLabel()" ng-model="label"/>'+
442                     '<div class="label label-danger" ng-if="empty_label">{{empty_label_string}}</div>'+
443                 '</div>'+
444                 '<div class="col-xs-1">'+
445                     '<select ng-disabled="record == 0" class="form-control" ng-model="suffix" ng-change="updateSuffix()" ng-options="s.label() for s in suffix_list"/>'+
446                 '</div>'+
447                 '<div ng-hide="onlyVols" class="col-xs-1"><input ng-disabled="record == 0" class="form-control" type="number" ng-model="copy_count" min="{{orig_copy_count}}" ng-change="changeCPCount()"></div>'+
448                 '<div ng-hide="onlyVols" class="col-xs-5">'+
449                     '<eg-vol-copy-edit record="{{record}}" ng-repeat="cp in copies track by idTracker(cp)" focus-next="focusNextBarcode" copy="cp" call-number="callNumber"></eg-vol-copy-edit>'+
450                 '</div>'+
451             '</div>',
452
453         scope: {focusNext: "=", allcopies: "=", copies: "=", onlyVols: "=", record: "@" },
454         controller : ['$scope','itemSvc','egCore',
455             function ( $scope , itemSvc , egCore ) {
456                 $scope.callNumber =  $scope.copies[0].call_number();
457                 if (!$scope.callNumber.label()) $scope.callNumber.emtpy_label = true;
458
459                 $scope.empty_label = false;
460                 $scope.empty_label_string = window.empty_label_string;
461
462                 $scope.idTracker = function (x) { if (x && x.id) return x.id() };
463
464                 // XXX $() is not working! arg
465                 $scope.focusNextBarcode = function (i, prev_bc) {
466                     var n;
467                     var yep = false;
468                     angular.forEach($scope.copies, function (cp) {
469                         if (n) return;
470
471                         if (cp.id() == i) {
472                             yep = true;
473                             return;
474                         }
475
476                         if (yep) n = cp.id();
477                     });
478
479                     if (n) {
480                         var next = '#' + $scope.callNumber.id() + '_' + n;
481                         var el = $(next);
482                         if (el) {
483                             if (!itemSvc.currently_generating) el.focus();
484                             if (prev_bc && itemSvc.auto_gen_barcode && el.val() == "") {
485                                 itemSvc.nextBarcode(prev_bc).then(function(bc){
486                                     el.focus();
487                                     el.val(bc);
488                                     el.trigger('change');
489                                 });
490                             } else {
491                                 itemSvc.currently_generating = false;
492                             }
493                         }
494                     } else {
495                         $scope.focusNext($scope.callNumber.id(),prev_bc)
496                     }
497                 }
498
499                 $scope.suffix_list = [];
500                 itemSvc.get_suffixes($scope.callNumber.owning_lib()).then(function(list){
501                     $scope.suffix_list = list;
502                     $scope.$watch('callNumber.suffix()', function (v) {
503                         if (angular.isObject(v)) v = v.id();
504                         $scope.suffix = $scope.suffix_list.filter( function (s) {
505                             return s.id() == v;
506                         })[0];
507                     });
508
509                 });
510                 $scope.updateSuffix = function () {
511                     angular.forEach($scope.copies, function(cp) {
512                         cp.call_number().suffix($scope.suffix);
513                         cp.call_number().ischanged(1);
514                     });
515                 }
516
517                 $scope.prefix_list = [];
518                 itemSvc.get_prefixes($scope.callNumber.owning_lib()).then(function(list){
519                     $scope.prefix_list = list;
520                     $scope.$watch('callNumber.prefix()', function (v) {
521                         if (angular.isObject(v)) v = v.id();
522                         $scope.prefix = $scope.prefix_list.filter(function (p) {
523                             return p.id() == v;
524                         })[0];
525                     });
526
527                 });
528                 $scope.updatePrefix = function () {
529                     angular.forEach($scope.copies, function(cp) {
530                         cp.call_number().prefix($scope.prefix);
531                         cp.call_number().ischanged(1);
532                     });
533                 }
534                 $scope.$watch('callNumber.owning_lib()', function(oldLib, newLib) {
535                     if (oldLib == newLib) return;
536                     var currentPrefix = $scope.callNumber.prefix();
537                     if (angular.isObject(currentPrefix)) currentPrefix = currentPrefix.id();
538                     itemSvc.get_prefixes($scope.callNumber.owning_lib()).then(function(list){
539                         $scope.prefix_list = list;
540                         var newPrefixId = $scope.prefix_list.filter(function (p) {
541                             return p.id() == currentPrefix;
542                         })[0] || -1;
543                         if (newPrefixId.id) newPrefixId = newPrefixId.id();
544                         $scope.prefix = $scope.prefix_list.filter(function (p) {
545                             return p.id() == newPrefixId;
546                         })[0];
547                         if ($scope.newPrefixId != currentPrefix) {
548                             $scope.callNumber.prefix($scope.prefix);
549                         }
550                     });
551                     var currentSuffix = $scope.callNumber.suffix();
552                     if (angular.isObject(currentSuffix)) currentSuffix = currentSuffix.id();
553                     itemSvc.get_suffixes($scope.callNumber.owning_lib()).then(function(list){
554                         $scope.suffix_list = list;
555                         var newSuffixId = $scope.suffix_list.filter(function (s) {
556                             return s.id() == currentSuffix;
557                         })[0] || -1;
558                         if (newSuffixId.id) newSuffixId = newSuffixId.id();
559                         $scope.suffix = $scope.suffix_list.filter(function (s) {
560                             return s.id() == newSuffixId;
561                         })[0];
562                         if ($scope.newSuffixId != currentSuffix) {
563                             $scope.callNumber.suffix($scope.suffix);
564                         }
565                     });
566                 });
567
568                 $scope.classification_list = [];
569                 itemSvc.get_classifications().then(function(list){
570                     $scope.classification_list = list;
571                     $scope.$watch('callNumber.label_class()', function (v) {
572                         if (angular.isObject(v)) v = v.id();
573                         $scope.classification = $scope.classification_list.filter(function (c) {
574                             return c.id() == v;
575                         })[0];
576                     });
577
578                 });
579                 $scope.updateClassification = function () {
580                     angular.forEach($scope.copies, function(cp) {
581                         cp.call_number().label_class($scope.classification);
582                         cp.call_number().ischanged(1);
583                     });
584                 }
585
586                 $scope.updateLabel = function () {
587                     if ($scope.label == '') {
588                         $scope.callNumber.empty_label = $scope.empty_label = true;
589                     } else {
590                         $scope.callNumber.empty_label = $scope.empty_label = false;
591                     }
592                     angular.forEach($scope.copies, function(cp) {
593                         cp.call_number().label($scope.label);
594                         cp.call_number().ischanged(1);
595                     });
596                 }
597
598                 $scope.$watch('callNumber.label()', function (v) {
599                     $scope.label = v;
600                 });
601
602                 $scope.prefix = $scope.callNumber.prefix();
603                 $scope.suffix = $scope.callNumber.suffix();
604                 $scope.classification = $scope.callNumber.label_class();
605                 $scope.label = $scope.callNumber.label();
606
607                 $scope.copy_count = $scope.copies.length;
608                 $scope.orig_copy_count = $scope.copy_count;
609
610                 $scope.changeCPCount = function () {
611                     while ($scope.copy_count > $scope.copies.length) {
612                         var cp = itemSvc.generateNewCopy(
613                             $scope.callNumber,
614                             $scope.callNumber.owning_lib(),
615                             $scope.fast_add,
616                             true
617                         );
618                         $scope.copies.push( cp );
619                         $scope.allcopies.push( cp );
620
621                     }
622
623                     if ($scope.copy_count >= $scope.orig_copy_count) {
624                         var how_many = $scope.copies.length - $scope.copy_count;
625                         if (how_many > 0) {
626                             var dead = $scope.copies.splice($scope.copy_count,how_many);
627                             $scope.callNumber.copies($scope.copies);
628
629                             // Trimming the global list is a bit more tricky
630                             angular.forEach( dead, function (d) {
631                                 angular.forEach( $scope.allcopies, function (l, i) { 
632                                     if (l === d) $scope.allcopies.splice(i,1);
633                                 });
634                             });
635                         }
636                     }
637                 }
638
639             }
640         ]
641
642     }
643 })
644
645 .directive("egVolEdit", function () {
646     return {
647         restrict: 'E',
648         replace: true,
649         template:
650             '<div class="row">'+
651                 '<div class="col-xs-1"><eg-org-selector alldisabled="{{record == 0}}" selected="owning_lib" disable-test="cant_have_vols"></eg-org-selector></div>'+
652                 '<div class="col-xs-1"><input ng-disabled="record == 0" class="form-control" type="number" min="{{orig_cn_count}}" ng-model="cn_count" ng-change="changeCNCount()"/></div>'+
653                 '<div class="col-xs-10">'+
654                     '<eg-vol-row only-vols="onlyVols" record="{{record}}"'+
655                         'ng-repeat="(cn,copies) in struct" '+
656                         'focus-next="focusNextFirst" copies="copies" allcopies="allcopies">'+
657                     '</eg-vol-row>'+
658                 '</div>'+
659             '</div>',
660
661         scope: { focusNext: "=", allcopies: "=", struct: "=", lib: "@", record: "@", onlyVols: "=" },
662         controller : ['$scope','itemSvc','egCore',
663             function ( $scope , itemSvc , egCore ) {
664                 $scope.first_cn = Object.keys($scope.struct)[0];
665                 $scope.full_cn = $scope.struct[$scope.first_cn][0].call_number();
666
667                 $scope.defaults = {};
668                 egCore.hatch.getItem('cat.copy.defaults').then(function(t) {
669                     if (t) {
670                         $scope.defaults = t;
671                     }
672                 });
673
674                 $scope.focusNextFirst = function(prev_cn,prev_bc) {
675                     var n;
676                     var yep = false;
677                     angular.forEach(Object.keys($scope.struct).sort(), function (cn) {
678                         if (n) return;
679
680                         if (cn == prev_cn) {
681                             yep = true;
682                             return;
683                         }
684
685                         if (yep) n = cn;
686                     });
687
688                     if (n) {
689                         var next = '#' + n + '_' + $scope.struct[n][0].id();
690                         var el = $(next);
691                         if (el) {
692                             if (!itemSvc.currently_generating) el.focus();
693                             if (prev_bc && itemSvc.auto_gen_barcode && el.val() == "") {
694                                 itemSvc.nextBarcode(prev_bc).then(function(bc){
695                                     el.focus();
696                                     el.val(bc);
697                                     el.trigger('change');
698                                 });
699                             } else {
700                                 itemSvc.currently_generating = false;
701                             }
702                         }
703                     } else {
704                         $scope.focusNext($scope.lib, prev_bc);
705                     }
706                 }
707
708                 $scope.cn_count = Object.keys($scope.struct).length;
709                 $scope.orig_cn_count = $scope.cn_count;
710
711                 $scope.owning_lib = egCore.org.get($scope.lib);
712                 $scope.$watch('owning_lib', function (oldLib, newLib) {
713                     if (oldLib == newLib) return;
714                     angular.forEach( Object.keys($scope.struct), function (cn) {
715                         $scope.struct[cn][0].call_number().owning_lib( $scope.owning_lib.id() );
716                         $scope.struct[cn][0].call_number().ischanged(1);
717                     });
718                 });
719
720                 $scope.cant_have_vols = function (id) { return !egCore.org.CanHaveVolumes(id); };
721
722                 $scope.$watch('cn_count', function (n) {
723                     var o = Object.keys($scope.struct).length;
724                     if (n > o) { // adding
725                         for (var i = o; o < n; o++) {
726                             var cn = new egCore.idl.acn();
727                             cn.id( --itemSvc.new_cn_id );
728                             cn.isnew( true );
729                             cn.prefix( $scope.defaults.prefix || -1 );
730                             cn.suffix( $scope.defaults.suffix || -1 );
731                             cn.label_class( $scope.defaults.classification || 1 );
732                             cn.owning_lib( $scope.owning_lib.id() );
733                             cn.record( $scope.full_cn.record() );
734
735                             var cp = itemSvc.generateNewCopy(
736                                 cn,
737                                 $scope.owning_lib.id(),
738                                 $scope.fast_add,
739                                 true
740                             );
741
742                             $scope.struct[cn.id()] = [cp];
743                             $scope.allcopies.push(cp);
744                             if (!$scope.defaults.classification) {
745                                 egCore.org.settings(
746                                     ['cat.default_classification_scheme'],
747                                     cn.owning_lib()
748                                 ).then(function (val) {
749                                     cn.label_class(val['cat.default_classification_scheme']);
750                                 });
751                             }
752                         }
753                     } else if (n < o && n >= $scope.orig_cn_count) { // removing
754                         var how_many = o - n;
755                         var list = Object
756                                 .keys($scope.struct)
757                                 .sort(function(a, b){return parseInt(a)-parseInt(b)})
758                                 .filter(function(x){ return parseInt(x) <= 0 });
759                         for (var i = 0; i < how_many; i++) {
760                             // Trimming the global list is a bit more tricky
761                             angular.forEach($scope.struct[list[i]], function (d) {
762                                 angular.forEach( $scope.allcopies, function (l, j) { 
763                                     if (l === d) $scope.allcopies.splice(j,1);
764                                 });
765                             });
766                             delete $scope.struct[list[i]];
767                         }
768                     }
769                 });
770             }
771         ]
772
773     }
774 })
775
776 /**
777  * Edit controller!
778  */
779 .controller('EditCtrl', 
780        ['$scope','$q','$window','$routeParams','$location','$timeout','egCore','egNet','egGridDataProvider','itemSvc','$uibModal',
781 function($scope , $q , $window , $routeParams , $location , $timeout , egCore , egNet , egGridDataProvider , itemSvc , $uibModal) {
782
783     $scope.forms = {}; // Accessed by t_attr_edit.tt2
784
785     $scope.defaults = { // If defaults are not set at all, allow everything
786         barcode_checkdigit : false,
787         auto_gen_barcode : false,
788         statcats : true,
789         copy_notes : true,
790         copy_tags : true,
791         attributes : {
792             status : true,
793             loan_duration : true,
794             fine_level : true,
795             cost : true,
796             alerts : true,
797             deposit : true,
798             deposit_amount : true,
799             opac_visible : true,
800             price : true,
801             circulate : true,
802             mint_condition : true,
803             circ_lib : true,
804             ref : true,
805             circ_modifier : true,
806             circ_as_type : true,
807             location : true,
808             holdable : true,
809             age_protect : true,
810             floating : true
811         }
812     };
813
814     $scope.new_lib_to_add = egCore.org.get(egCore.auth.user().ws_ou());
815     $scope.changeNewLib = function (org) {
816         $scope.new_lib_to_add = org;
817     }
818     $scope.addLibToStruct = function () {
819         var newLib = $scope.new_lib_to_add;
820         var cn = new egCore.idl.acn();
821         cn.id( --itemSvc.new_cn_id );
822         cn.isnew( true );
823         cn.prefix( $scope.defaults.prefix || -1 );
824         cn.suffix( $scope.defaults.suffix || -1 );
825         cn.label_class( $scope.defaults.classification || 1 );
826         cn.owning_lib( newLib.id() );
827         cn.record( $scope.record_id );
828
829         var cp = itemSvc.generateNewCopy(
830             cn,
831             newLib.id(),
832             $scope.fast_add,
833             true
834         );
835
836         $scope.data.addCopy(cp);
837
838         if (!$scope.defaults.classification) {
839             egCore.org.settings(
840                 ['cat.default_classification_scheme'],
841                 cn.owning_lib()
842             ).then(function (val) {
843                 cn.label_class(val['cat.default_classification_scheme']);
844             });
845         }
846     }
847
848     $scope.embedded = ($routeParams.mode && $routeParams.mode == 'embedded') ? true : false;
849     $scope.edit_templates = ($location.path().match(/edit_template/)) ? true : false;
850
851     $scope.saveDefaults = function () {
852         egCore.hatch.setItem('cat.copy.defaults', $scope.defaults);
853     }
854
855     $scope.fetchDefaults = function () {
856         egCore.hatch.getItem('cat.copy.defaults').then(function(t) {
857             if (t) {
858                 $scope.defaults = t;
859                 if (!$scope.batch) $scope.batch = {};
860                 $scope.batch.classification = $scope.defaults.classification;
861                 $scope.batch.prefix = $scope.defaults.prefix;
862                 $scope.batch.suffix = $scope.defaults.suffix;
863                 $scope.working.statcat_filter = $scope.defaults.statcat_filter;
864                 if (
865                         typeof $scope.defaults.statcat_filter == 'object' &&
866                         Object.keys($scope.defaults.statcat_filter).length > 0
867                    ) {
868                     // want fieldmapper object here...
869                     $scope.defaults.statcat_filter =
870                          egCore.idl.Clone($scope.defaults.statcat_filter);
871                     // ... and ID here
872                     $scope.working.statcat_filter = $scope.defaults.statcat_filter.id();
873                 }
874                 if ($scope.defaults.always_volumes) $scope.show_vols = true;
875                 if ($scope.defaults.barcode_checkdigit) itemSvc.barcode_checkdigit = true;
876                 if ($scope.defaults.auto_gen_barcode) itemSvc.auto_gen_barcode = true;
877             }
878         });
879     }
880     $scope.fetchDefaults();
881
882     $scope.$watch('defaults.statcat_filter', function() {
883         $scope.saveDefaults();
884     });
885     $scope.$watch('defaults.auto_gen_barcode', function (n,o) {
886         itemSvc.auto_gen_barcode = n
887     });
888
889     $scope.$watch('defaults.barcode_checkdigit', function (n,o) {
890         itemSvc.barcode_checkdigit = n
891     });
892
893     $scope.dirty = false;
894     $scope.$watch('dirty',
895         function(newVal, oldVal) {
896             if (newVal && newVal != oldVal) {
897                 $($window).on('beforeunload.edit', function(){
898                     return 'There is unsaved data!'
899                 });
900             } else {
901                 $($window).off('beforeunload.edit');
902             }
903         }
904     );
905
906     $scope.only_vols = false;
907     $scope.show_vols = true;
908     $scope.show_copies = true;
909
910     $scope.tracker = function (x,f) { if (x) return x[f]() };
911     $scope.idTracker = function (x) { if (x) return $scope.tracker(x,'id') };
912     $scope.cant_have_vols = function (id) { return !egCore.org.CanHaveVolumes(id); };
913
914     $scope.orgById = function (id) { return egCore.org.get(id) }
915     $scope.statusById = function (id) {
916         return $scope.status_list.filter( function (s) { return s.id() == id } )[0];
917     }
918     $scope.locationById = function (id) {
919         return $scope.location_cache[''+id];
920     }
921
922     $scope.workingToComplete = function () {
923         angular.forEach( $scope.workingGridControls.selectedItems(), function (c) {
924             angular.forEach( itemSvc.copies, function (w, i) {
925                 if (c === w)
926                     $scope.completed_copies = $scope.completed_copies.concat(itemSvc.copies.splice(i,1));
927             });
928         });
929
930         return true;
931     }
932
933     $scope.completeToWorking = function () {
934         angular.forEach( $scope.completedGridControls.selectedItems(), function (c) {
935             angular.forEach( $scope.completed_copies, function (w, i) {
936                 if (c === w)
937                     itemSvc.copies = itemSvc.copies.concat($scope.completed_copies.splice(i,1));
938             });
939         });
940
941         return true;
942     }
943
944     createSimpleUpdateWatcher = function (field,exclude_copies_with_one_of_these_values) {
945         return $scope.$watch('working.' + field, function () {
946             var newval = $scope.working[field];
947
948             if (typeof newval != 'undefined') {
949                 if (angular.isObject(newval)) { // we'll use the pkey
950                     if (newval.id) newval = newval.id();
951                     else if (newval.code) newval = newval.code();
952                 }
953
954                 if (""+newval == "" || newval == null) {
955                     $scope.working[field] = undefined;
956                     newval = null;
957                 }
958
959                 if ($scope.workingGridControls && $scope.workingGridControls.selectedItems) {
960                     angular.forEach(
961                         $scope.workingGridControls.selectedItems(),
962                         function (cp) {
963                             if (exclude_copies_with_one_of_these_values
964                                 && exclude_copies_with_one_of_these_values.indexOf(cp[field](),0) > -1) {
965                                 return;
966                             }
967                             if (cp[field]() !== newval) {
968                                 cp[field](newval);
969                                 cp.ischanged(1);
970                                 $scope.dirty = true;
971                             }
972                         }
973                     );
974                 }
975             }
976         });
977     }
978
979     $scope.working = {
980         statcats: {},
981         statcat_filter: undefined
982     };
983
984     $scope.statcatUpdate = function (id) {
985         var newval = $scope.working.statcats[id];
986
987         if (typeof newval != 'undefined') {
988             if (angular.isObject(newval)) { // we'll use the pkey
989                 newval = newval.id();
990             }
991     
992             if (""+newval == "" || newval == null) {
993                 $scope.working.statcats[id] = undefined;
994                 newval = null;
995             }
996     
997             if (!$scope.in_item_select && $scope.workingGridControls && $scope.workingGridControls.selectedItems) {
998                 angular.forEach(
999                     $scope.workingGridControls.selectedItems(),
1000                     function (cp) {
1001                         $scope.dirty = true;
1002
1003                         cp.stat_cat_entries(
1004                             angular.forEach( cp.stat_cat_entries(), function (e) {
1005                                 if (e.stat_cat() == id) { // mark deleted
1006                                     e.isdeleted(1);
1007                                 }
1008                             })
1009                         );
1010     
1011                         if (newval) {
1012                             var e = new egCore.idl.asce();
1013                             e.isnew( 1 );
1014                             e.stat_cat( id );
1015                             e.id(newval);
1016
1017                             cp.stat_cat_entries(
1018                                 cp.stat_cat_entries() ?
1019                                     cp.stat_cat_entries().concat([ e ]) :
1020                                     [ e ]
1021                             );
1022
1023                         }
1024
1025                         // trim out all deleted ones; the API used to
1026                         // do the update doesn't actually consult
1027                         // isdeleted for stat cat entries
1028                         cp.stat_cat_entries(
1029                             cp.stat_cat_entries().filter(function (e) {
1030                                 return !Boolean(e.isdeleted());
1031                             })
1032                         );
1033    
1034                         cp.ischanged(1);
1035                     }
1036                 );
1037             }
1038         }
1039     }
1040
1041     var dataKey = $routeParams.dataKey;
1042     console.debug('dataKey: ' + dataKey);
1043
1044     if ((dataKey && dataKey.length > 0) || $scope.edit_templates) {
1045
1046         $scope.templates = {};
1047         $scope.template_name = '';
1048         $scope.template_name_list = [];
1049
1050         $scope.fetchTemplates = function () {
1051             egCore.hatch.getItem('cat.copy.templates').then(function(t) {
1052                 if (t) {
1053                     $scope.templates = t;
1054                     $scope.template_name_list = Object.keys(t);
1055                 }
1056             });
1057             egCore.hatch.getItem('cat.copy.last_template').then(function(t) {
1058                 if (t) $scope.template_name = t;
1059             });
1060         }
1061         $scope.fetchTemplates();
1062
1063         $scope.applyTemplate = function (n) {
1064             angular.forEach($scope.templates[n], function (v,k) {
1065                 if (k == 'circ_lib') {
1066                     $scope.working[k] = egCore.org.get(v);
1067                 } else if (!angular.isObject(v)) {
1068                     $scope.working[k] = angular.copy(v);
1069                 } else {
1070                     angular.forEach(v, function (sv,sk) {
1071                         if (k == 'callnumber') {
1072                             angular.forEach(v, function (cnv,cnk) {
1073                                 $scope.batch[cnk] = cnv;
1074                             });
1075                             $scope.applyBatchCNValues();
1076                         } else {
1077                             $scope.working[k][sk] = angular.copy(sv);
1078                             if (k == 'statcats') $scope.statcatUpdate(sk);
1079                         }
1080                     });
1081                 }
1082             });
1083             egCore.hatch.setItem('cat.copy.last_template', n);
1084         }
1085
1086         $scope.copytab = 'working';
1087         $scope.tab = 'edit';
1088         $scope.summaryRecord = null;
1089         $scope.record_id = null;
1090         $scope.data = {};
1091         $scope.completed_copies = [];
1092         $scope.location_orgs = [];
1093         $scope.location_cache = {};
1094         $scope.statcats = [];
1095         if (!$scope.batch) $scope.batch = {};
1096
1097         $scope.applyBatchCNValues = function () {
1098             if ($scope.data.tree) {
1099                 angular.forEach($scope.data.tree, function(cn_hash) {
1100                     angular.forEach(cn_hash, function(copies) {
1101                         angular.forEach(copies, function(cp) {
1102                             if (typeof $scope.batch.classification != 'undefined' && $scope.batch.classification != '') {
1103                                 var label_class = $scope.classification_list.filter(function(p){ return p.id() == $scope.batch.classification })[0];
1104                                 cp.call_number().label_class(label_class);
1105                                 cp.call_number().ischanged(1);
1106                                 $scope.dirty = true;
1107                             }
1108                             if (typeof $scope.batch.prefix != 'undefined' && $scope.batch.prefix != '') {
1109                                 var prefix = $scope.prefix_list.filter(function(p){ return p.id() == $scope.batch.prefix })[0];
1110                                 cp.call_number().prefix(prefix);
1111                                 cp.call_number().ischanged(1);
1112                                 $scope.dirty = true;
1113                             }
1114                             if (typeof $scope.batch.label != 'undefined' && $scope.batch.label != '') {
1115                                 cp.call_number().label($scope.batch.label);
1116                                 cp.call_number().ischanged(1);
1117                                 $scope.dirty = true;
1118                             }
1119                             if (typeof $scope.batch.suffix != 'undefined' && $scope.batch.suffix != '') {
1120                                 var suffix = $scope.suffix_list.filter(function(p){ return p.id() == $scope.batch.suffix })[0];
1121                                 cp.call_number().suffix(suffix);
1122                                 cp.call_number().ischanged(1);
1123                                 $scope.dirty = true;
1124                             }
1125                         });
1126                     });
1127                 });
1128             }
1129         }
1130
1131         $scope.clearWorking = function () {
1132             angular.forEach($scope.working, function (v,k,o) {
1133                 if (!angular.isObject(v)) {
1134                     if (typeof v != 'undefined')
1135                         $scope.working[k] = undefined;
1136                 } else if (k != 'circ_lib') {
1137                     angular.forEach(v, function (sv,sk) {
1138                         if (typeof v != 'undefined')
1139                             $scope.working[k][sk] = undefined;
1140                     });
1141                 }
1142             });
1143             $scope.working.circ_lib = undefined; // special
1144         }
1145
1146         $scope.completedGridDataProvider = egGridDataProvider.instance({
1147             get : function(offset, count) {
1148                 //return provider.arrayNotifier(itemSvc.copies, offset, count);
1149                 return this.arrayNotifier($scope.completed_copies, offset, count);
1150             }
1151         });
1152
1153         $scope.completedGridControls = {};
1154
1155         $scope.workingGridDataProvider = egGridDataProvider.instance({
1156             get : function(offset, count) {
1157                 //return provider.arrayNotifier(itemSvc.copies, offset, count);
1158                 return this.arrayNotifier(itemSvc.copies, offset, count);
1159             }
1160         });
1161
1162         $scope.workingGridControls = {};
1163         $scope.add_vols_copies = false;
1164         $scope.is_fast_add = false;
1165
1166         egNet.request(
1167             'open-ils.actor',
1168             'open-ils.actor.anon_cache.get_value',
1169             dataKey, 'edit-these-copies'
1170         ).then(function (data) {
1171
1172             if (data) {
1173                 if (data.hide_vols && !$scope.defaults.always_volumes) $scope.show_vols = false;
1174                 if (data.hide_copies) {
1175                     $scope.show_copies = false;
1176                     $scope.only_vols = true;
1177                 }
1178
1179                 $scope.record_id = data.record_id;
1180
1181                 function fetchRaw () {
1182                     if (!$scope.only_vols) $scope.dirty = true;
1183                     $scope.add_vols_copies = true;
1184
1185                     /* data.raw data structure looks like this:
1186                      * [{
1187                      *      callnumber : $cn_id, // optional, to add a copy to a cn
1188                      *      owner      : $org, // optional, defaults to ws_ou
1189                      *      label      : $cn_label, // optional, to supply a label on a new cn
1190                      *      barcode    : $cp_barcode // optional, to supply a barcode on a new cp
1191                      *      fast_add   : boolean // optional, to specify whether this came
1192                      *                              in as a fast add
1193                      * },...]
1194                      * 
1195                      * All can be left out and a completely empty vol/copy combo will be vivicated.
1196                      */
1197
1198                     angular.forEach(
1199                         data.raw,
1200                         function (proto) {
1201                             if (proto.fast_add) $scope.is_fast_add = true;
1202                             if (proto.callnumber) {
1203                                 return egCore.pcrud.retrieve('acn', proto.callnumber)
1204                                 .then(function(cn) {
1205                                     var cp = new itemSvc.generateNewCopy(
1206                                         cn,
1207                                         proto.owner || egCore.auth.user().ws_ou(),
1208                                         $scope.is_fast_add,
1209                                         ((!$scope.only_vols) ? true : false)
1210                                     );
1211
1212                                     if (proto.barcode) {
1213                                         cp.barcode( proto.barcode );
1214                                         cp.empty_barcode = false;
1215                                     }
1216
1217                                     itemSvc.addCopy(cp)
1218                                 });
1219                             } else {
1220                                 var cn = new egCore.idl.acn();
1221                                 cn.id( --itemSvc.new_cn_id );
1222                                 cn.isnew( true );
1223                                 cn.prefix( $scope.defaults.prefix || -1 );
1224                                 cn.suffix( $scope.defaults.suffix || -1 );
1225                                 cn.owning_lib( proto.owner || egCore.auth.user().ws_ou() );
1226                                 cn.record( $scope.record_id );
1227                                 egCore.org.settings(
1228                                     ['cat.default_classification_scheme'],
1229                                     cn.owning_lib()
1230                                 ).then(function (val) {
1231                                     cn.label_class(
1232                                         $scope.defaults.classification ||
1233                                         val['cat.default_classification_scheme'] ||
1234                                         1
1235                                     );
1236                                     if (proto.label) {
1237                                         cn.label( proto.label );
1238                                     } else {
1239                                         egCore.net.request(
1240                                             'open-ils.cat',
1241                                             'open-ils.cat.biblio.record.marc_cn.retrieve',
1242                                             $scope.record_id,
1243                                             cn.label_class()
1244                                         ).then(function(cn_array) {
1245                                             if (cn_array.length > 0) {
1246                                                 for (var field in cn_array[0]) {
1247                                                     cn.label( cn_array[0][field] );
1248                                                     break;
1249                                                 }
1250                                             }
1251                                         });
1252                                     }
1253                                 });
1254
1255                                 var cp = new itemSvc.generateNewCopy(
1256                                     cn,
1257                                     proto.owner || egCore.auth.user().ws_ou(),
1258                                     $scope.is_fast_add,
1259                                     true
1260                                 );
1261
1262                                 if (proto.barcode) {
1263                                     cp.barcode( proto.barcode );
1264                                     cp.empty_barcode = false;
1265                                 }
1266
1267                                 itemSvc.addCopy(cp)
1268                             }
1269     
1270                         }
1271                     );
1272
1273                     return itemSvc.copies;
1274                 }
1275
1276                 if (data.copies && data.copies.length)
1277                     return itemSvc.fetchIds(data.copies).then(fetchRaw);
1278
1279                 return fetchRaw();
1280
1281             }
1282
1283         }).then( function() {
1284             $scope.data = itemSvc;
1285             $scope.workingGridDataProvider.refresh();
1286         });
1287
1288         $scope.can_save = false;
1289         function check_saveable () {
1290             var can_save = true;
1291             angular.forEach(
1292                 itemSvc.copies,
1293                 function (i) {
1294                     if (i.duplicate_barcode || i.empty_barcode || i.call_number().empty_label)
1295                         can_save = false;
1296                 }
1297             );
1298             if ($scope.forms.myForm && $scope.forms.myForm.$invalid) {
1299                 can_save = false;
1300             }
1301             $scope.can_save = can_save;
1302         }
1303
1304         $scope.disableSave = function () {
1305             check_saveable();
1306             return !$scope.can_save;
1307         }
1308
1309         $scope.focusNextFirst = function(prev_lib,prev_bc) {
1310             var n;
1311             var yep = false;
1312             angular.forEach(Object.keys($scope.data.tree).sort(), function (lib) {
1313                 if (n) return;
1314
1315                 if (lib == prev_lib) {
1316                     yep = true;
1317                     return;
1318                 }
1319
1320                 if (yep) n = lib;
1321             });
1322
1323             if (n) {
1324                 var first_cn = Object.keys($scope.data.tree[n])[0];
1325                 var next = '#' + first_cn + '_' + $scope.data.tree[n][first_cn][0].id();
1326                 var el = $(next);
1327                 if (el) {
1328                     if (!itemSvc.currently_generating) el.focus();
1329                     if (prev_bc && itemSvc.auto_gen_barcode && el.val() == "") {
1330                         itemSvc.nextBarcode(prev_bc).then(function(bc){
1331                             el.focus();
1332                             el.val(bc);
1333                             el.trigger('change');
1334                         });
1335                     } else {
1336                         itemSvc.currently_generating = false;
1337                     }
1338                 }
1339             }
1340         }
1341
1342         $scope.in_item_select = false;
1343         $scope.afterItemSelect = function() { $scope.in_item_select = false };
1344         $scope.handleItemSelect = function (item_list) {
1345             if (item_list && item_list.length > 0) {
1346                 $scope.in_item_select = true;
1347
1348                 angular.forEach(Object.keys($scope.defaults.attributes), function (attr) {
1349
1350                     var value_hash = {};
1351                     angular.forEach(item_list, function (item) {
1352                         if (item[attr]) {
1353                             var v = item[attr]()
1354                             if (angular.isObject(v)) {
1355                                 if (v.id) v = v.id();
1356                                 else if (v.code) v = v.code();
1357                             }
1358                             value_hash[v] = 1;
1359                         }
1360                     });
1361
1362                     if (Object.keys(value_hash).length == 1) {
1363                         if (attr == 'circ_lib') {
1364                             $scope.working[attr] = egCore.org.get(item_list[0][attr]());
1365                         } else {
1366                             $scope.working[attr] = item_list[0][attr]();
1367                         }
1368                     } else {
1369                         $scope.working[attr] = undefined;
1370                     }
1371                 });
1372
1373                 angular.forEach($scope.statcats, function (sc) {
1374
1375                     var counter = -1;
1376                     var value_hash = {};
1377                     var none = false;
1378                     angular.forEach(item_list, function (item) {
1379                         if (item.stat_cat_entries()) {
1380                             if (item.stat_cat_entries().length > 0) {
1381                                 var right_sc = item.stat_cat_entries().filter(function (e) {
1382                                     return e.stat_cat() == sc.id() && !Boolean(e.isdeleted());
1383                                 });
1384
1385                                 if (right_sc.length > 0) {
1386                                     value_hash[right_sc[0].id()] = right_sc[0].id();
1387                                 } else {
1388                                     none = true;
1389                                 }
1390                             }
1391                         } else {
1392                             none = true;
1393                         }
1394                     });
1395
1396                     if (!none && Object.keys(value_hash).length == 1) {
1397                         $scope.working.statcats[sc.id()] = value_hash[Object.keys(value_hash)[0]];
1398                     } else {
1399                         $scope.working.statcats[sc.id()] = undefined;
1400                     }
1401                 });
1402
1403             } else {
1404                 $scope.clearWorking();
1405             }
1406
1407         }
1408
1409         $scope.$watch('data.copies.length', function () {
1410             if ($scope.data.copies) {
1411                 var base_orgs = $scope.data.copies.map(function(cp){
1412                     return cp.circ_lib()
1413                 }).concat(
1414                     $scope.data.copies.map(function(cp){
1415                         return cp.call_number().owning_lib()
1416                     })
1417                 ).concat(
1418                     [egCore.auth.user().ws_ou()]
1419                 ).filter(function(e,i,a){
1420                     return a.lastIndexOf(e) === i;
1421                 });
1422
1423                 var all_orgs = [];
1424                 angular.forEach(base_orgs, function(o) {
1425                     all_orgs = all_orgs.concat( egCore.org.fullPath(o, true) );
1426                 });
1427
1428                 var final_orgs = all_orgs.filter(function(e,i,a){
1429                     return a.lastIndexOf(e) === i;
1430                 }).sort(function(a, b){return parseInt(a)-parseInt(b)});
1431
1432                 if ($scope.location_orgs.toString() != final_orgs.toString()) {
1433                     $scope.location_orgs = final_orgs;
1434                     if ($scope.location_orgs.length) {
1435                         itemSvc.get_locations($scope.location_orgs).then(function(list){
1436                             angular.forEach(list, function(l) {
1437                                 $scope.location_cache[ ''+l.id() ] = l;
1438                             });
1439                             $scope.location_list = list;
1440                         });
1441
1442                         $scope.statcat_filter_list = [];
1443                         angular.forEach($scope.location_orgs, function (o) {
1444                             $scope.statcat_filter_list.push(egCore.org.get(o));
1445                         });
1446
1447                         itemSvc.get_statcats($scope.location_orgs).then(function(list){
1448                             $scope.statcats = list;
1449                             angular.forEach($scope.statcats, function (s) {
1450
1451                                 if (!$scope.working)
1452                                     $scope.working = { statcats: {}, statcat_filter: undefined};
1453                                 if (!$scope.working.statcats)
1454                                     $scope.working.statcats = {};
1455
1456                                 if (!$scope.in_item_select) {
1457                                     $scope.working.statcats[s.id()] = undefined;
1458                                 }
1459                                 createStatcatUpdateWatcher(s.id());
1460                             });
1461                             $scope.in_item_select = false;
1462                             // do a refresh here to work around a race
1463                             // condition that can result in stat cats
1464                             // not being selected.
1465                             $scope.workingGridDataProvider.refresh();
1466                         });
1467                     }
1468                 }
1469             }
1470
1471             $scope.workingGridDataProvider.refresh();
1472         });
1473
1474         $scope.statcat_visible = function (sc_owner) {
1475             var visible = typeof $scope.working.statcat_filter === 'undefined' || !$scope.working.statcat_filter;
1476             angular.forEach(egCore.org.ancestors(sc_owner), function (ancestor_org) {
1477                 if ($scope.working.statcat_filter == ancestor_org.id())
1478                     visible = true;
1479             });
1480             return visible;
1481         }
1482
1483         $scope.suffix_list = [];
1484         itemSvc.get_suffixes(egCore.auth.user().ws_ou()).then(function(list){
1485             $scope.suffix_list = list;
1486         });
1487
1488         $scope.prefix_list = [];
1489         itemSvc.get_prefixes(egCore.auth.user().ws_ou()).then(function(list){
1490             $scope.prefix_list = list;
1491         });
1492
1493         $scope.classification_list = [];
1494         itemSvc.get_classifications().then(function(list){
1495             $scope.classification_list = list;
1496         });
1497
1498         $scope.$watch('completed_copies.length', function () {
1499             $scope.completedGridDataProvider.refresh();
1500         });
1501
1502         $scope.location_list = [];
1503         itemSvc.get_locations().then(function(list){
1504             $scope.location_list = list;
1505         });
1506         createSimpleUpdateWatcher('location');
1507
1508         $scope.status_list = [];
1509         itemSvc.get_magic_statuses().then(function(list){
1510             $scope.magic_status_list = list;
1511             createSimpleUpdateWatcher('status',$scope.magic_status_list);
1512         });
1513         itemSvc.get_statuses().then(function(list){
1514             $scope.status_list = list;
1515         });
1516
1517         $scope.circ_modifier_list = [];
1518         itemSvc.get_circ_mods().then(function(list){
1519             $scope.circ_modifier_list = list;
1520         });
1521         createSimpleUpdateWatcher('circ_modifier');
1522
1523         $scope.circ_type_list = [];
1524         itemSvc.get_circ_types().then(function(list){
1525             $scope.circ_type_list = list;
1526         });
1527         createSimpleUpdateWatcher('circ_as_type');
1528
1529         $scope.age_protect_list = [];
1530         itemSvc.get_age_protects().then(function(list){
1531             $scope.age_protect_list = list;
1532         });
1533         createSimpleUpdateWatcher('age_protect');
1534
1535         $scope.floating_list = [];
1536         itemSvc.get_floating_groups().then(function(list){
1537             $scope.floating_list = list;
1538         });
1539         createSimpleUpdateWatcher('floating');
1540
1541         createSimpleUpdateWatcher('circ_lib');
1542         createSimpleUpdateWatcher('circulate');
1543         createSimpleUpdateWatcher('holdable');
1544         createSimpleUpdateWatcher('fine_level');
1545         createSimpleUpdateWatcher('loan_duration');
1546         createSimpleUpdateWatcher('price');
1547         createSimpleUpdateWatcher('cost');
1548         createSimpleUpdateWatcher('deposit');
1549         createSimpleUpdateWatcher('deposit_amount');
1550         createSimpleUpdateWatcher('mint_condition');
1551         createSimpleUpdateWatcher('opac_visible');
1552         createSimpleUpdateWatcher('ref');
1553
1554         $scope.saveCompletedCopies = function (and_exit) {
1555             var cnHash = {};
1556             var perCnCopies = {};
1557             angular.forEach( $scope.completed_copies, function (cp) {
1558                 var cn = cp.call_number();
1559                 var cn_cps = cp.call_number().copies();
1560                 cp.call_number().copies([]);
1561                 var cn_id = cp.call_number().id();
1562                 cp.call_number(cn_id); // prevent loops in JSON-ification
1563                 if (!cnHash[cn_id]) {
1564                     cnHash[cn_id] = egCore.idl.Clone(cn);
1565                     perCnCopies[cn_id] = [egCore.idl.Clone(cp)];
1566                 } else {
1567                     perCnCopies[cn_id].push(egCore.idl.Clone(cp));
1568                 }
1569                 cp.call_number(cn); // put the data back
1570                 cp.call_number().copies(cn_cps);
1571                 if (typeof cnHash[cn_id].prefix() == 'object')
1572                     cnHash[cn_id].prefix(cnHash[cn_id].prefix().id()); // un-object-ize some fields
1573                 if (typeof cnHash[cn_id].suffix() == 'object')
1574                     cnHash[cn_id].suffix(cnHash[cn_id].suffix().id()); // un-object-ize some fields
1575             });
1576
1577             angular.forEach(perCnCopies, function (v, k) {
1578                 cnHash[k].copies(v);
1579             });
1580
1581             cnList = [];
1582             angular.forEach(cnHash, function (v, k) {
1583                 cnList.push(v);
1584             });
1585
1586             egNet.request(
1587                 'open-ils.cat',
1588                 'open-ils.cat.asset.volume.fleshed.batch.update.override',
1589                 egCore.auth.token(), cnList, 1, { auto_merge_vols : 1, create_parts : 1 }
1590             ).then(function(update_count) {
1591                 if (and_exit) {
1592                     $scope.dirty = false;
1593                     $timeout(function(){$window.close()});
1594                 }
1595             });
1596         }
1597
1598         $scope.saveAndContinue = function () {
1599             $scope.saveCompletedCopies(false);
1600         }
1601
1602         $scope.workingSaveAndExit = function () {
1603             $scope.workingToComplete();
1604             $scope.saveAndExit();
1605         }
1606
1607         $scope.saveAndExit = function () {
1608             $scope.saveCompletedCopies(true);
1609         }
1610
1611     }
1612
1613     $scope.copy_notes_dialog = function(copy_list) {
1614         var default_pub = Boolean($scope.defaults.copy_notes_pub);
1615         if (!angular.isArray(copy_list)) copy_list = [copy_list];
1616
1617         return $uibModal.open({
1618             templateUrl: './cat/volcopy/t_copy_notes',
1619             animation: true,
1620             controller:
1621                    ['$scope','$uibModalInstance',
1622             function($scope , $uibModalInstance) {
1623                 $scope.focusNote = true;
1624                 $scope.note = {
1625                     creator : egCore.auth.user().id(),
1626                     title   : '',
1627                     value   : '',
1628                     pub     : default_pub,
1629                 };
1630
1631                 $scope.require_initials = false;
1632                 egCore.org.settings([
1633                     'ui.staff.require_initials.copy_notes'
1634                 ]).then(function(set) {
1635                     $scope.require_initials = Boolean(set['ui.staff.require_initials.copy_notes']);
1636                 });
1637
1638                 $scope.note_list = [];
1639                 if (copy_list.length == 1) {
1640                     $scope.note_list = copy_list[0].notes();
1641                 }
1642
1643                 $scope.ok = function(note) {
1644
1645                     if (note.initials) note.value += ' [' + note.initials + ']';
1646                     angular.forEach(copy_list, function (cp) {
1647                         if (!angular.isArray(cp.notes())) cp.notes([]);
1648                         var n = new egCore.idl.acpn();
1649                         n.isnew(1);
1650                         n.creator(note.creator);
1651                         n.pub(note.pub);
1652                         n.title(note.title);
1653                         n.value(note.value);
1654                         n.owning_copy(cp.id());
1655                         cp.notes().push( n );
1656                     });
1657
1658                     $uibModalInstance.close();
1659                 }
1660
1661                 $scope.cancel = function($event) {
1662                     $uibModalInstance.dismiss();
1663                     $event.preventDefault();
1664                 }
1665             }]
1666         });
1667     }
1668
1669     $scope.copy_tags_dialog = function(copy_list) {
1670         if (!angular.isArray(copy_list)) copy_list = [copy_list];
1671
1672         return $uibModal.open({
1673             templateUrl: './cat/volcopy/t_copy_tags',
1674             animation: true,
1675             controller:
1676                    ['$scope','$uibModalInstance',
1677             function($scope , $uibModalInstance) {
1678
1679                 $scope.tag_map = [];
1680                 var tag_hash = {};
1681                 var shared_tags = {};
1682                 angular.forEach(copy_list, function (cp) {
1683                     angular.forEach(cp.tags(), function(tag) {
1684                         if (!(tag.tag().id() in shared_tags)) {
1685                             shared_tags[tag.tag().id()] = 1;
1686                         } else {
1687                             shared_tags[tag.tag().id()]++;
1688                         }
1689                         if (!(tag.tag().id() in tag_hash)) {
1690                             tag_hash[tag.tag().id()] = tag;
1691                         }
1692                     });
1693                 });
1694                 angular.forEach(tag_hash, function(value, key) {
1695                     if (shared_tags[key] == copy_list.length) {
1696                         $scope.tag_map.push(value);
1697                     }
1698                 });
1699
1700                 $scope.tag_types = [];
1701                 egCore.pcrud.retrieveAll('cctt', {order_by : { cctt : 'label' }}, {atomic : true}).then(function(list) {
1702                     $scope.tag_types = list;
1703                     $scope.tag_type = $scope.tag_types[0].code(); // just pick a default
1704                 });
1705
1706                 $scope.getTags = function(val) {
1707                     return egCore.pcrud.search('acpt',
1708                         { 
1709                             owner :  egCore.org.fullPath(egCore.auth.user().ws_ou(), true),
1710                             label : { 'startwith' : {
1711                                         transform: 'evergreen.lowercase',
1712                                         value : [ 'evergreen.lowercase', val ]
1713                                     }},
1714                             tag_type : $scope.tag_type
1715                         },
1716                         { order_by : { 'acpt' : ['label'] } }, { atomic: true }
1717                     ).then(function(list) {
1718                         return list.map(function(item) {
1719                             return item.label();
1720                         });
1721                     });
1722                 }
1723
1724                 $scope.addTag = function() {
1725                     var tagLabel = $scope.selectedLabel;
1726                     // clear the typeahead
1727                     $scope.selectedLabel = "";
1728
1729                     // first, check tags already associated with the copy
1730                     var foundMatch = false;
1731                     angular.forEach($scope.tag_map, function(tag) {
1732                         if (tag.tag().label() ==  tagLabel && tag.tag().tag_type() == $scope.tag_type) {
1733                             foundMatch = true;
1734                             if (tag.isdeleted()) tag.isdeleted(0); // just deleting the mapping
1735                         }
1736                     });
1737                     if (!foundMatch) {
1738                         egCore.pcrud.search('acpt',
1739                             { 
1740                                 owner : egCore.org.fullPath(egCore.auth.user().ws_ou(), true),
1741                                 label : tagLabel,
1742                                 tag_type : $scope.tag_type
1743                             },
1744                             { order_by : { 'acpt' : ['label'] } }, { atomic: true }
1745                         ).then(function(list) {
1746                             if (list.length > 0) {
1747                                 var newMap = new egCore.idl.acptcm();
1748                                 newMap.isnew(1);
1749                                 newMap.copy(copy_list[0].id());
1750                                 newMap.tag(egCore.idl.Clone(list[0]));
1751                                 $scope.tag_map.push(newMap);
1752                             } else {
1753                                 var newTag = new egCore.idl.acpt();
1754                                 newTag.isnew(1);
1755                                 newTag.owner(egCore.auth.user().ws_ou());
1756                                 newTag.label(tagLabel);
1757                                 newTag.pub('t');
1758                                 newTag.tag_type($scope.tag_type);
1759
1760                                 var newMap = new egCore.idl.acptcm();
1761                                 newMap.isnew(1);
1762                                 newMap.copy(copy_list[0].id());
1763                                 newMap.tag(newTag);
1764                                 $scope.tag_map.push(newMap);
1765                             }
1766                         });
1767                     }
1768                 }
1769
1770                 $scope.ok = function(note) {
1771                     // in the multi-item case, this works OK for
1772                     // adding new maps to existing tags, but doesn't handle
1773                     // all possibilities
1774                     angular.forEach(copy_list, function (cp) {
1775                         cp.tags($scope.tag_map);
1776                     });
1777                     $uibModalInstance.close();
1778                 }
1779
1780                 $scope.cancel = function($event) {
1781                     $uibModalInstance.dismiss();
1782                     $event.preventDefault();
1783                 }
1784             }]
1785         });
1786     }
1787
1788 }])
1789
1790 .directive("egVolTemplate", function () {
1791     return {
1792         restrict: 'E',
1793         replace: true,
1794         template: '<div ng-include="'+"'/eg/staff/cat/volcopy/t_attr_edit'"+'"></div>',
1795         scope: {
1796             editTemplates: '=',
1797         },
1798         controller : ['$scope','$window','itemSvc','egCore','ngToast',
1799             function ( $scope , $window , itemSvc , egCore , ngToast) {
1800
1801                 $scope.defaults = { // If defaults are not set at all, allow everything
1802                     barcode_checkdigit : false,
1803                     auto_gen_barcode : false,
1804                     statcats : true,
1805                     copy_notes : true,
1806                     copy_tags : true,
1807                     attributes : {
1808                         status : true,
1809                         loan_duration : true,
1810                         fine_level : true,
1811                         cost : true,
1812                         alerts : true,
1813                         deposit : true,
1814                         deposit_amount : true,
1815                         opac_visible : true,
1816                         price : true,
1817                         circulate : true,
1818                         mint_condition : true,
1819                         circ_lib : true,
1820                         ref : true,
1821                         circ_modifier : true,
1822                         circ_as_type : true,
1823                         location : true,
1824                         holdable : true,
1825                         age_protect : true,
1826                         floating : true
1827                     }
1828                 };
1829
1830                 $scope.fetchDefaults = function () {
1831                     egCore.hatch.getItem('cat.copy.defaults').then(function(t) {
1832                         if (t) {
1833                             $scope.defaults = t;
1834                             $scope.working.statcat_filter = $scope.defaults.statcat_filter;
1835                             if (
1836                                     typeof $scope.defaults.statcat_filter == 'object' &&
1837                                     Object.keys($scope.defaults.statcat_filter).length > 0
1838                                 ) {
1839                                 // want fieldmapper object here...
1840                                 $scope.defaults.statcat_filter =
1841                                     egCore.idl.Clone($scope.defaults.statcat_filter);
1842                                 // ... and ID here
1843                                 $scope.working.statcat_filter = $scope.defaults.statcat_filter.id();
1844                             }
1845                         }
1846                     });
1847                 }
1848                 $scope.fetchDefaults();
1849
1850                 $scope.dirty = false;
1851                 $scope.$watch('dirty',
1852                     function(newVal, oldVal) {
1853                         if (newVal && newVal != oldVal) {
1854                             $($window).on('beforeunload.template', function(){
1855                                 return 'There is unsaved template data!'
1856                             });
1857                         } else {
1858                             $($window).off('beforeunload.template');
1859                         }
1860                     }
1861                 );
1862
1863                 $scope.template_controls = true;
1864
1865                 $scope.fetchTemplates = function () {
1866                     egCore.hatch.getItem('cat.copy.templates').then(function(t) {
1867                         if (t) {
1868                             $scope.templates = t;
1869                             $scope.template_name_list = Object.keys(t);
1870                         }
1871                     });
1872                 }
1873                 $scope.fetchTemplates();
1874             
1875                 $scope.applyTemplate = function (n) {
1876                     angular.forEach($scope.templates[n], function (v,k) {
1877                         if (k == 'circ_lib') {
1878                             $scope.working[k] = egCore.org.get(v);
1879                         } else if (!angular.isObject(v)) {
1880                             $scope.working[k] = angular.copy(v);
1881                         } else {
1882                             angular.forEach(v, function (sv,sk) {
1883                                 if (!(k in $scope.working))
1884                                     $scope.working[k] = {};
1885                                 $scope.working[k][sk] = angular.copy(sv);
1886                             });
1887                         }
1888                     });
1889                     $scope.template_name = '';
1890                 }
1891
1892                 $scope.deleteTemplate = function (n) {
1893                     if (n) {
1894                         delete $scope.templates[n]
1895                         $scope.template_name_list = Object.keys($scope.templates);
1896                         $scope.template_name = '';
1897                         egCore.hatch.setItem('cat.copy.templates', $scope.templates);
1898                         $scope.$parent.fetchTemplates();
1899                         ngToast.create(egCore.strings.VOL_COPY_TEMPLATE_SUCCESS_DELETE);
1900                     }
1901                 }
1902
1903                 $scope.saveTemplate = function (n) {
1904                     if (n) {
1905                         var tmpl = {};
1906             
1907                         angular.forEach($scope.working, function (v,k) {
1908                             if (angular.isObject(v)) { // we'll use the pkey
1909                                 if (v.id) v = v.id();
1910                                 else if (v.code) v = v.code();
1911                             }
1912             
1913                             tmpl[k] = v;
1914                         });
1915             
1916                         $scope.templates[n] = tmpl;
1917                         $scope.template_name_list = Object.keys($scope.templates);
1918             
1919                         egCore.hatch.setItem('cat.copy.templates', $scope.templates);
1920                         $scope.$parent.fetchTemplates();
1921
1922                         $scope.dirty = false;
1923                     } else {
1924                         // save all templates, as we might do after an import
1925                         egCore.hatch.setItem('cat.copy.templates', $scope.templates);
1926                         $scope.$parent.fetchTemplates();
1927                     }
1928                     ngToast.create(egCore.strings.VOL_COPY_TEMPLATE_SUCCESS_SAVE);
1929                 }
1930             
1931                 $scope.templates = {};
1932                 $scope.imported_templates = { data : '' };
1933                 $scope.template_name = '';
1934                 $scope.template_name_list = [];
1935
1936                 $scope.$watch('imported_templates.data', function(newVal, oldVal) {
1937                     if (newVal && newVal != oldVal) {
1938                         try {
1939                             var newTemplates = JSON.parse(newVal);
1940                             if (!Object.keys(newTemplates).length) return;
1941                             $scope.templates = newTemplates;
1942                             $scope.template_name_list = Object.keys(newTemplates);
1943                             $scope.template_name = '';
1944                         } catch (E) {
1945                             console.log('tried to import an invalid copy template file');
1946                         }
1947                     }
1948                 });
1949
1950                 $scope.tracker = function (x,f) { if (x) return x[f]() };
1951                 $scope.idTracker = function (x) { if (x) return $scope.tracker(x,'id') };
1952                 $scope.cant_have_vols = function (id) { return !egCore.org.CanHaveVolumes(id); };
1953             
1954                 $scope.orgById = function (id) { return egCore.org.get(id) }
1955                 $scope.statusById = function (id) {
1956                     return $scope.status_list.filter( function (s) { return s.id() == id } )[0];
1957                 }
1958                 $scope.locationById = function (id) {
1959                     return $scope.location_cache[''+id];
1960                 }
1961             
1962                 createSimpleUpdateWatcher = function (field) {
1963                     $scope.$watch('working.' + field, function () {
1964                         var newval = $scope.working[field];
1965             
1966                         if (typeof newval != 'undefined') {
1967                             $scope.dirty = true;
1968                             if (angular.isObject(newval)) { // we'll use the pkey
1969                                 if (newval.id) $scope.working[field] = newval.id();
1970                                 else if (newval.code) $scope.working[field] = newval.code();
1971                             }
1972             
1973                             if (""+newval == "" || newval == null) {
1974                                 $scope.working[field] = undefined;
1975                             }
1976             
1977                         }
1978                     });
1979                 }
1980             
1981                 $scope.working = {
1982                     statcats: {},
1983                     statcat_filter: undefined
1984                 };
1985             
1986                 $scope.statcat_visible = function (sc_owner) {
1987                     var visible = typeof $scope.working.statcat_filter === 'undefined' || !$scope.working.statcat_filter;
1988                     angular.forEach(egCore.org.ancestors(sc_owner), function (ancestor_org) {
1989                         if ($scope.working.statcat_filter == ancestor_org.id())
1990                             visible = true;
1991                     });
1992                     return visible;
1993                 }
1994
1995                 createStatcatUpdateWatcher = function (id) {
1996                     return $scope.$watch('working.statcats[' + id + ']', function () {
1997                         if ($scope.working.statcats) {
1998                             var newval = $scope.working.statcats[id];
1999                 
2000                             if (typeof newval != 'undefined') {
2001                                 $scope.dirty = true;
2002                                 if (angular.isObject(newval)) { // we'll use the pkey
2003                                     newval = newval.id();
2004                                 }
2005                 
2006                                 if (""+newval == "" || newval == null) {
2007                                     $scope.working.statcats[id] = undefined;
2008                                     newval = null;
2009                                 }
2010                 
2011                             }
2012                         }
2013                     });
2014                 }
2015
2016                 $scope.clearWorking = function () {
2017                     angular.forEach($scope.working, function (v,k,o) {
2018                         if (!angular.isObject(v)) {
2019                             if (typeof v != 'undefined')
2020                                 $scope.working[k] = undefined;
2021                         } else if (k != 'circ_lib') {
2022                             angular.forEach(v, function (sv,sk) {
2023                                 $scope.working[k][sk] = undefined;
2024                             });
2025                         }
2026                     });
2027                     $scope.working.circ_lib = undefined; // special
2028                     $scope.dirty = false;
2029                 }
2030
2031                 $scope.working = {};
2032                 $scope.location_orgs = [];
2033                 $scope.location_cache = {};
2034             
2035                 $scope.location_list = [];
2036                 itemSvc.get_locations(
2037                     egCore.org.fullPath( egCore.auth.user().ws_ou(), true )
2038                 ).then(function(list){
2039                     $scope.location_list = list;
2040                 });
2041                 createSimpleUpdateWatcher('location');
2042
2043                 $scope.statcat_filter_list = egCore.org.fullPath( egCore.auth.user().ws_ou() );
2044
2045                 $scope.statcats = [];
2046                 itemSvc.get_statcats(
2047                     egCore.org.fullPath( egCore.auth.user().ws_ou(), true )
2048                 ).then(function(list){
2049                     $scope.statcats = list;
2050                     angular.forEach($scope.statcats, function (s) {
2051
2052                         if (!$scope.working)
2053                             $scope.working = { statcats: {}, statcat_filter: undefined};
2054                         if (!$scope.working.statcats)
2055                             $scope.working.statcats = {};
2056
2057                         $scope.working.statcats[s.id()] = undefined;
2058                         createStatcatUpdateWatcher(s.id());
2059                     });
2060                 });
2061             
2062                 $scope.status_list = [];
2063                 itemSvc.get_magic_statuses().then(function(list){
2064                     $scope.magic_status_list = list;
2065                 });
2066                 itemSvc.get_statuses().then(function(list){
2067                     $scope.status_list = list;
2068                 });
2069                 createSimpleUpdateWatcher('status');
2070             
2071                 $scope.circ_modifier_list = [];
2072                 itemSvc.get_circ_mods().then(function(list){
2073                     $scope.circ_modifier_list = list;
2074                 });
2075                 createSimpleUpdateWatcher('circ_modifier');
2076             
2077                 $scope.circ_type_list = [];
2078                 itemSvc.get_circ_types().then(function(list){
2079                     $scope.circ_type_list = list;
2080                 });
2081                 createSimpleUpdateWatcher('circ_as_type');
2082             
2083                 $scope.age_protect_list = [];
2084                 itemSvc.get_age_protects().then(function(list){
2085                     $scope.age_protect_list = list;
2086                 });
2087                 createSimpleUpdateWatcher('age_protect');
2088             
2089                 createSimpleUpdateWatcher('circulate');
2090                 createSimpleUpdateWatcher('holdable');
2091                 createSimpleUpdateWatcher('fine_level');
2092                 createSimpleUpdateWatcher('loan_duration');
2093                 createSimpleUpdateWatcher('cost');
2094                 createSimpleUpdateWatcher('deposit');
2095                 createSimpleUpdateWatcher('deposit_amount');
2096                 createSimpleUpdateWatcher('mint_condition');
2097                 createSimpleUpdateWatcher('opac_visible');
2098                 createSimpleUpdateWatcher('ref');
2099
2100                 $scope.suffix_list = [];
2101                 itemSvc.get_suffixes(egCore.auth.user().ws_ou()).then(function(list){
2102                     $scope.suffix_list = list;
2103                 });
2104
2105                 $scope.prefix_list = [];
2106                 itemSvc.get_prefixes(egCore.auth.user().ws_ou()).then(function(list){
2107                     $scope.prefix_list = list;
2108                 });
2109
2110                 $scope.classification_list = [];
2111                 itemSvc.get_classifications().then(function(list){
2112                     $scope.classification_list = list;
2113                 });
2114
2115                 createSimpleUpdateWatcher('working.callnumber.classification');
2116                 createSimpleUpdateWatcher('working.callnumber.prefix');
2117                 createSimpleUpdateWatcher('working.callnumber.suffix');
2118             }
2119         ]
2120     }
2121 })
2122
2123