LP#1673857: add ability to set copy tags in volume/copy editor
[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) cp.barcode( proto.barcode );
1213
1214                                     itemSvc.addCopy(cp)
1215                                 });
1216                             } else {
1217                                 var cn = new egCore.idl.acn();
1218                                 cn.id( --itemSvc.new_cn_id );
1219                                 cn.isnew( true );
1220                                 cn.prefix( $scope.defaults.prefix || -1 );
1221                                 cn.suffix( $scope.defaults.suffix || -1 );
1222                                 cn.owning_lib( proto.owner || egCore.auth.user().ws_ou() );
1223                                 cn.record( $scope.record_id );
1224                                 egCore.org.settings(
1225                                     ['cat.default_classification_scheme'],
1226                                     cn.owning_lib()
1227                                 ).then(function (val) {
1228                                     cn.label_class(
1229                                         $scope.defaults.classification ||
1230                                         val['cat.default_classification_scheme'] ||
1231                                         1
1232                                     );
1233                                     if (proto.label) {
1234                                         cn.label( proto.label );
1235                                     } else {
1236                                         egCore.net.request(
1237                                             'open-ils.cat',
1238                                             'open-ils.cat.biblio.record.marc_cn.retrieve',
1239                                             $scope.record_id,
1240                                             cn.label_class()
1241                                         ).then(function(cn_array) {
1242                                             if (cn_array.length > 0) {
1243                                                 for (var field in cn_array[0]) {
1244                                                     cn.label( cn_array[0][field] );
1245                                                     break;
1246                                                 }
1247                                             }
1248                                         });
1249                                     }
1250                                 });
1251
1252                                 var cp = new itemSvc.generateNewCopy(
1253                                     cn,
1254                                     proto.owner || egCore.auth.user().ws_ou(),
1255                                     $scope.is_fast_add,
1256                                     true
1257                                 );
1258
1259                                 if (proto.barcode) cp.barcode( proto.barcode );
1260
1261                                 itemSvc.addCopy(cp)
1262                             }
1263     
1264                         }
1265                     );
1266
1267                     return itemSvc.copies;
1268                 }
1269
1270                 if (data.copies && data.copies.length)
1271                     return itemSvc.fetchIds(data.copies).then(fetchRaw);
1272
1273                 return fetchRaw();
1274
1275             }
1276
1277         }).then( function() {
1278             $scope.data = itemSvc;
1279             $scope.workingGridDataProvider.refresh();
1280         });
1281
1282         $scope.can_save = false;
1283         function check_saveable () {
1284             var can_save = true;
1285             angular.forEach(
1286                 itemSvc.copies,
1287                 function (i) {
1288                     if (i.duplicate_barcode || i.empty_barcode || i.call_number().empty_label)
1289                         can_save = false;
1290                 }
1291             );
1292             if ($scope.forms.myForm && $scope.forms.myForm.$invalid) {
1293                 can_save = false;
1294             }
1295             $scope.can_save = can_save;
1296         }
1297
1298         $scope.disableSave = function () {
1299             check_saveable();
1300             return !$scope.can_save;
1301         }
1302
1303         $scope.focusNextFirst = function(prev_lib,prev_bc) {
1304             var n;
1305             var yep = false;
1306             angular.forEach(Object.keys($scope.data.tree).sort(), function (lib) {
1307                 if (n) return;
1308
1309                 if (lib == prev_lib) {
1310                     yep = true;
1311                     return;
1312                 }
1313
1314                 if (yep) n = lib;
1315             });
1316
1317             if (n) {
1318                 var first_cn = Object.keys($scope.data.tree[n])[0];
1319                 var next = '#' + first_cn + '_' + $scope.data.tree[n][first_cn][0].id();
1320                 var el = $(next);
1321                 if (el) {
1322                     if (!itemSvc.currently_generating) el.focus();
1323                     if (prev_bc && itemSvc.auto_gen_barcode && el.val() == "") {
1324                         itemSvc.nextBarcode(prev_bc).then(function(bc){
1325                             el.focus();
1326                             el.val(bc);
1327                             el.trigger('change');
1328                         });
1329                     } else {
1330                         itemSvc.currently_generating = false;
1331                     }
1332                 }
1333             }
1334         }
1335
1336         $scope.in_item_select = false;
1337         $scope.afterItemSelect = function() { $scope.in_item_select = false };
1338         $scope.handleItemSelect = function (item_list) {
1339             if (item_list && item_list.length > 0) {
1340                 $scope.in_item_select = true;
1341
1342                 angular.forEach(Object.keys($scope.defaults.attributes), function (attr) {
1343
1344                     var value_hash = {};
1345                     angular.forEach(item_list, function (item) {
1346                         if (item[attr]) {
1347                             var v = item[attr]()
1348                             if (angular.isObject(v)) {
1349                                 if (v.id) v = v.id();
1350                                 else if (v.code) v = v.code();
1351                             }
1352                             value_hash[v] = 1;
1353                         }
1354                     });
1355
1356                     if (Object.keys(value_hash).length == 1) {
1357                         if (attr == 'circ_lib') {
1358                             $scope.working[attr] = egCore.org.get(item_list[0][attr]());
1359                         } else {
1360                             $scope.working[attr] = item_list[0][attr]();
1361                         }
1362                     } else {
1363                         $scope.working[attr] = undefined;
1364                     }
1365                 });
1366
1367                 angular.forEach($scope.statcats, function (sc) {
1368
1369                     var counter = -1;
1370                     var value_hash = {};
1371                     var none = false;
1372                     angular.forEach(item_list, function (item) {
1373                         if (item.stat_cat_entries()) {
1374                             if (item.stat_cat_entries().length > 0) {
1375                                 var right_sc = item.stat_cat_entries().filter(function (e) {
1376                                     return e.stat_cat() == sc.id() && !Boolean(e.isdeleted());
1377                                 });
1378
1379                                 if (right_sc.length > 0) {
1380                                     value_hash[right_sc[0].id()] = right_sc[0].id();
1381                                 } else {
1382                                     none = true;
1383                                 }
1384                             }
1385                         } else {
1386                             none = true;
1387                         }
1388                     });
1389
1390                     if (!none && Object.keys(value_hash).length == 1) {
1391                         $scope.working.statcats[sc.id()] = value_hash[Object.keys(value_hash)[0]];
1392                     } else {
1393                         $scope.working.statcats[sc.id()] = undefined;
1394                     }
1395                 });
1396
1397             } else {
1398                 $scope.clearWorking();
1399             }
1400
1401         }
1402
1403         $scope.$watch('data.copies.length', function () {
1404             if ($scope.data.copies) {
1405                 var base_orgs = $scope.data.copies.map(function(cp){
1406                     return cp.circ_lib()
1407                 }).concat(
1408                     $scope.data.copies.map(function(cp){
1409                         return cp.call_number().owning_lib()
1410                     })
1411                 ).concat(
1412                     [egCore.auth.user().ws_ou()]
1413                 ).filter(function(e,i,a){
1414                     return a.lastIndexOf(e) === i;
1415                 });
1416
1417                 var all_orgs = [];
1418                 angular.forEach(base_orgs, function(o) {
1419                     all_orgs = all_orgs.concat( egCore.org.fullPath(o, true) );
1420                 });
1421
1422                 var final_orgs = all_orgs.filter(function(e,i,a){
1423                     return a.lastIndexOf(e) === i;
1424                 }).sort(function(a, b){return parseInt(a)-parseInt(b)});
1425
1426                 if ($scope.location_orgs.toString() != final_orgs.toString()) {
1427                     $scope.location_orgs = final_orgs;
1428                     if ($scope.location_orgs.length) {
1429                         itemSvc.get_locations($scope.location_orgs).then(function(list){
1430                             angular.forEach(list, function(l) {
1431                                 $scope.location_cache[ ''+l.id() ] = l;
1432                             });
1433                             $scope.location_list = list;
1434                         });
1435
1436                         $scope.statcat_filter_list = [];
1437                         angular.forEach($scope.location_orgs, function (o) {
1438                             $scope.statcat_filter_list.push(egCore.org.get(o));
1439                         });
1440
1441                         itemSvc.get_statcats($scope.location_orgs).then(function(list){
1442                             $scope.statcats = list;
1443                             angular.forEach($scope.statcats, function (s) {
1444
1445                                 if (!$scope.working)
1446                                     $scope.working = { statcats: {}, statcat_filter: undefined};
1447                                 if (!$scope.working.statcats)
1448                                     $scope.working.statcats = {};
1449
1450                                 if (!$scope.in_item_select) {
1451                                     $scope.working.statcats[s.id()] = undefined;
1452                                 }
1453                                 createStatcatUpdateWatcher(s.id());
1454                             });
1455                             $scope.in_item_select = false;
1456                             // do a refresh here to work around a race
1457                             // condition that can result in stat cats
1458                             // not being selected.
1459                             $scope.workingGridDataProvider.refresh();
1460                         });
1461                     }
1462                 }
1463             }
1464
1465             $scope.workingGridDataProvider.refresh();
1466         });
1467
1468         $scope.statcat_visible = function (sc_owner) {
1469             var visible = typeof $scope.working.statcat_filter === 'undefined' || !$scope.working.statcat_filter;
1470             angular.forEach(egCore.org.ancestors(sc_owner), function (ancestor_org) {
1471                 if ($scope.working.statcat_filter == ancestor_org.id())
1472                     visible = true;
1473             });
1474             return visible;
1475         }
1476
1477         $scope.suffix_list = [];
1478         itemSvc.get_suffixes(egCore.auth.user().ws_ou()).then(function(list){
1479             $scope.suffix_list = list;
1480         });
1481
1482         $scope.prefix_list = [];
1483         itemSvc.get_prefixes(egCore.auth.user().ws_ou()).then(function(list){
1484             $scope.prefix_list = list;
1485         });
1486
1487         $scope.classification_list = [];
1488         itemSvc.get_classifications().then(function(list){
1489             $scope.classification_list = list;
1490         });
1491
1492         $scope.$watch('completed_copies.length', function () {
1493             $scope.completedGridDataProvider.refresh();
1494         });
1495
1496         $scope.location_list = [];
1497         itemSvc.get_locations().then(function(list){
1498             $scope.location_list = list;
1499         });
1500         createSimpleUpdateWatcher('location');
1501
1502         $scope.status_list = [];
1503         itemSvc.get_magic_statuses().then(function(list){
1504             $scope.magic_status_list = list;
1505             createSimpleUpdateWatcher('status',$scope.magic_status_list);
1506         });
1507         itemSvc.get_statuses().then(function(list){
1508             $scope.status_list = list;
1509         });
1510
1511         $scope.circ_modifier_list = [];
1512         itemSvc.get_circ_mods().then(function(list){
1513             $scope.circ_modifier_list = list;
1514         });
1515         createSimpleUpdateWatcher('circ_modifier');
1516
1517         $scope.circ_type_list = [];
1518         itemSvc.get_circ_types().then(function(list){
1519             $scope.circ_type_list = list;
1520         });
1521         createSimpleUpdateWatcher('circ_as_type');
1522
1523         $scope.age_protect_list = [];
1524         itemSvc.get_age_protects().then(function(list){
1525             $scope.age_protect_list = list;
1526         });
1527         createSimpleUpdateWatcher('age_protect');
1528
1529         $scope.floating_list = [];
1530         itemSvc.get_floating_groups().then(function(list){
1531             $scope.floating_list = list;
1532         });
1533         createSimpleUpdateWatcher('floating');
1534
1535         createSimpleUpdateWatcher('circ_lib');
1536         createSimpleUpdateWatcher('circulate');
1537         createSimpleUpdateWatcher('holdable');
1538         createSimpleUpdateWatcher('fine_level');
1539         createSimpleUpdateWatcher('loan_duration');
1540         createSimpleUpdateWatcher('price');
1541         createSimpleUpdateWatcher('cost');
1542         createSimpleUpdateWatcher('deposit');
1543         createSimpleUpdateWatcher('deposit_amount');
1544         createSimpleUpdateWatcher('mint_condition');
1545         createSimpleUpdateWatcher('opac_visible');
1546         createSimpleUpdateWatcher('ref');
1547
1548         $scope.saveCompletedCopies = function (and_exit) {
1549             var cnHash = {};
1550             var perCnCopies = {};
1551             angular.forEach( $scope.completed_copies, function (cp) {
1552                 var cn = cp.call_number();
1553                 var cn_cps = cp.call_number().copies();
1554                 cp.call_number().copies([]);
1555                 var cn_id = cp.call_number().id();
1556                 cp.call_number(cn_id); // prevent loops in JSON-ification
1557                 if (!cnHash[cn_id]) {
1558                     cnHash[cn_id] = egCore.idl.Clone(cn);
1559                     perCnCopies[cn_id] = [egCore.idl.Clone(cp)];
1560                 } else {
1561                     perCnCopies[cn_id].push(egCore.idl.Clone(cp));
1562                 }
1563                 cp.call_number(cn); // put the data back
1564                 cp.call_number().copies(cn_cps);
1565                 if (typeof cnHash[cn_id].prefix() == 'object')
1566                     cnHash[cn_id].prefix(cnHash[cn_id].prefix().id()); // un-object-ize some fields
1567                 if (typeof cnHash[cn_id].suffix() == 'object')
1568                     cnHash[cn_id].suffix(cnHash[cn_id].suffix().id()); // un-object-ize some fields
1569             });
1570
1571             angular.forEach(perCnCopies, function (v, k) {
1572                 cnHash[k].copies(v);
1573             });
1574
1575             cnList = [];
1576             angular.forEach(cnHash, function (v, k) {
1577                 cnList.push(v);
1578             });
1579
1580             egNet.request(
1581                 'open-ils.cat',
1582                 'open-ils.cat.asset.volume.fleshed.batch.update.override',
1583                 egCore.auth.token(), cnList, 1, { auto_merge_vols : 1, create_parts : 1 }
1584             ).then(function(update_count) {
1585                 if (and_exit) {
1586                     $scope.dirty = false;
1587                     $timeout(function(){$window.close()});
1588                 }
1589             });
1590         }
1591
1592         $scope.saveAndContinue = function () {
1593             $scope.saveCompletedCopies(false);
1594         }
1595
1596         $scope.workingSaveAndExit = function () {
1597             $scope.workingToComplete();
1598             $scope.saveAndExit();
1599         }
1600
1601         $scope.saveAndExit = function () {
1602             $scope.saveCompletedCopies(true);
1603         }
1604
1605     }
1606
1607     $scope.copy_notes_dialog = function(copy_list) {
1608         var default_pub = Boolean($scope.defaults.copy_notes_pub);
1609         if (!angular.isArray(copy_list)) copy_list = [copy_list];
1610
1611         return $uibModal.open({
1612             templateUrl: './cat/volcopy/t_copy_notes',
1613             animation: true,
1614             controller:
1615                    ['$scope','$uibModalInstance',
1616             function($scope , $uibModalInstance) {
1617                 $scope.focusNote = true;
1618                 $scope.note = {
1619                     creator : egCore.auth.user().id(),
1620                     title   : '',
1621                     value   : '',
1622                     pub     : default_pub,
1623                 };
1624
1625                 $scope.require_initials = false;
1626                 egCore.org.settings([
1627                     'ui.staff.require_initials.copy_notes'
1628                 ]).then(function(set) {
1629                     $scope.require_initials = Boolean(set['ui.staff.require_initials.copy_notes']);
1630                 });
1631
1632                 $scope.note_list = [];
1633                 if (copy_list.length == 1) {
1634                     $scope.note_list = copy_list[0].notes();
1635                 }
1636
1637                 $scope.ok = function(note) {
1638
1639                     if (note.initials) note.value += ' [' + note.initials + ']';
1640                     angular.forEach(copy_list, function (cp) {
1641                         if (!angular.isArray(cp.notes())) cp.notes([]);
1642                         var n = new egCore.idl.acpn();
1643                         n.isnew(1);
1644                         n.creator(note.creator);
1645                         n.pub(note.pub);
1646                         n.title(note.title);
1647                         n.value(note.value);
1648                         n.owning_copy(cp.id());
1649                         cp.notes().push( n );
1650                     });
1651
1652                     $uibModalInstance.close();
1653                 }
1654
1655                 $scope.cancel = function($event) {
1656                     $uibModalInstance.dismiss();
1657                     $event.preventDefault();
1658                 }
1659             }]
1660         });
1661     }
1662
1663     $scope.copy_tags_dialog = function(copy_list) {
1664         if (!angular.isArray(copy_list)) copy_list = [copy_list];
1665
1666         return $uibModal.open({
1667             templateUrl: './cat/volcopy/t_copy_tags',
1668             animation: true,
1669             controller:
1670                    ['$scope','$uibModalInstance',
1671             function($scope , $uibModalInstance) {
1672
1673                 $scope.tag_map = [];
1674                 var tag_hash = {};
1675                 var shared_tags = {};
1676                 angular.forEach(copy_list, function (cp) {
1677                     angular.forEach(cp.tags(), function(tag) {
1678                         if (!(tag.tag().id() in shared_tags)) {
1679                             shared_tags[tag.tag().id()] = 1;
1680                         } else {
1681                             shared_tags[tag.tag().id()]++;
1682                         }
1683                         if (!(tag.tag().id() in tag_hash)) {
1684                             tag_hash[tag.tag().id()] = tag;
1685                         }
1686                     });
1687                 });
1688                 angular.forEach(tag_hash, function(value, key) {
1689                     if (shared_tags[key] == copy_list.length) {
1690                         $scope.tag_map.push(value);
1691                     }
1692                 });
1693
1694                 $scope.tag_types = [];
1695                 egCore.pcrud.retrieveAll('cctt', {order_by : { cctt : 'label' }}, {atomic : true}).then(function(list) {
1696                     $scope.tag_types = list;
1697                     $scope.tag_type = $scope.tag_types[0].code(); // just pick a default
1698                 });
1699
1700                 $scope.getTags = function(val) {
1701                     return egCore.pcrud.search('acpt',
1702                         { 
1703                             owner :  egCore.org.fullPath(egCore.auth.user().ws_ou(), true),
1704                             label : { 'startwith' : {
1705                                         transform: 'evergreen.lowercase',
1706                                         value : [ 'evergreen.lowercase', val ]
1707                                     }},
1708                             tag_type : $scope.tag_type
1709                         },
1710                         { order_by : { 'acpt' : ['label'] } }, { atomic: true }
1711                     ).then(function(list) {
1712                         return list.map(function(item) {
1713                             return item.label();
1714                         });
1715                     });
1716                 }
1717
1718                 $scope.addTag = function() {
1719                     var tagLabel = $scope.selectedLabel;
1720                     // clear the typeahead
1721                     $scope.selectedLabel = "";
1722
1723                     // first, check tags already associated with the copy
1724                     var foundMatch = false;
1725                     angular.forEach($scope.tag_map, function(tag) {
1726                         if (tag.tag().label() ==  tagLabel && tag.tag().tag_type() == $scope.tag_type) {
1727                             foundMatch = true;
1728                             if (tag.isdeleted()) tag.isdeleted(0); // just deleting the mapping
1729                         }
1730                     });
1731                     if (!foundMatch) {
1732                         egCore.pcrud.search('acpt',
1733                             { 
1734                                 owner : egCore.org.fullPath(egCore.auth.user().ws_ou(), true),
1735                                 label : tagLabel,
1736                                 tag_type : $scope.tag_type
1737                             },
1738                             { order_by : { 'acpt' : ['label'] } }, { atomic: true }
1739                         ).then(function(list) {
1740                             if (list.length > 0) {
1741                                 var newMap = new egCore.idl.acptcm();
1742                                 newMap.isnew(1);
1743                                 newMap.copy(copy_list[0].id());
1744                                 newMap.tag(egCore.idl.Clone(list[0]));
1745                                 $scope.tag_map.push(newMap);
1746                             } else {
1747                                 var newTag = new egCore.idl.acpt();
1748                                 newTag.isnew(1);
1749                                 newTag.owner(egCore.auth.user().ws_ou());
1750                                 newTag.label(tagLabel);
1751                                 newTag.pub('t');
1752                                 newTag.tag_type($scope.tag_type);
1753
1754                                 var newMap = new egCore.idl.acptcm();
1755                                 newMap.isnew(1);
1756                                 newMap.copy(copy_list[0].id());
1757                                 newMap.tag(newTag);
1758                                 $scope.tag_map.push(newMap);
1759                             }
1760                         });
1761                     }
1762                 }
1763
1764                 $scope.ok = function(note) {
1765                     // in the multi-item case, this works OK for
1766                     // adding new maps to existing tags, but doesn't handle
1767                     // all possibilities
1768                     angular.forEach(copy_list, function (cp) {
1769                         cp.tags($scope.tag_map);
1770                     });
1771                     $uibModalInstance.close();
1772                 }
1773
1774                 $scope.cancel = function($event) {
1775                     $uibModalInstance.dismiss();
1776                     $event.preventDefault();
1777                 }
1778             }]
1779         });
1780     }
1781
1782 }])
1783
1784 .directive("egVolTemplate", function () {
1785     return {
1786         restrict: 'E',
1787         replace: true,
1788         template: '<div ng-include="'+"'/eg/staff/cat/volcopy/t_attr_edit'"+'"></div>',
1789         scope: {
1790             editTemplates: '=',
1791         },
1792         controller : ['$scope','$window','itemSvc','egCore','ngToast',
1793             function ( $scope , $window , itemSvc , egCore , ngToast) {
1794
1795                 $scope.defaults = { // If defaults are not set at all, allow everything
1796                     barcode_checkdigit : false,
1797                     auto_gen_barcode : false,
1798                     statcats : true,
1799                     copy_notes : true,
1800                     copy_tags : true,
1801                     attributes : {
1802                         status : true,
1803                         loan_duration : true,
1804                         fine_level : true,
1805                         cost : true,
1806                         alerts : true,
1807                         deposit : true,
1808                         deposit_amount : true,
1809                         opac_visible : true,
1810                         price : true,
1811                         circulate : true,
1812                         mint_condition : true,
1813                         circ_lib : true,
1814                         ref : true,
1815                         circ_modifier : true,
1816                         circ_as_type : true,
1817                         location : true,
1818                         holdable : true,
1819                         age_protect : true,
1820                         floating : true
1821                     }
1822                 };
1823
1824                 $scope.fetchDefaults = function () {
1825                     egCore.hatch.getItem('cat.copy.defaults').then(function(t) {
1826                         if (t) {
1827                             $scope.defaults = t;
1828                             $scope.working.statcat_filter = $scope.defaults.statcat_filter;
1829                             if (
1830                                     typeof $scope.defaults.statcat_filter == 'object' &&
1831                                     Object.keys($scope.defaults.statcat_filter).length > 0
1832                                 ) {
1833                                 // want fieldmapper object here...
1834                                 $scope.defaults.statcat_filter =
1835                                     egCore.idl.Clone($scope.defaults.statcat_filter);
1836                                 // ... and ID here
1837                                 $scope.working.statcat_filter = $scope.defaults.statcat_filter.id();
1838                             }
1839                         }
1840                     });
1841                 }
1842                 $scope.fetchDefaults();
1843
1844                 $scope.dirty = false;
1845                 $scope.$watch('dirty',
1846                     function(newVal, oldVal) {
1847                         if (newVal && newVal != oldVal) {
1848                             $($window).on('beforeunload.template', function(){
1849                                 return 'There is unsaved template data!'
1850                             });
1851                         } else {
1852                             $($window).off('beforeunload.template');
1853                         }
1854                     }
1855                 );
1856
1857                 $scope.template_controls = true;
1858
1859                 $scope.fetchTemplates = function () {
1860                     egCore.hatch.getItem('cat.copy.templates').then(function(t) {
1861                         if (t) {
1862                             $scope.templates = t;
1863                             $scope.template_name_list = Object.keys(t);
1864                         }
1865                     });
1866                 }
1867                 $scope.fetchTemplates();
1868             
1869                 $scope.applyTemplate = function (n) {
1870                     angular.forEach($scope.templates[n], function (v,k) {
1871                         if (k == 'circ_lib') {
1872                             $scope.working[k] = egCore.org.get(v);
1873                         } else if (!angular.isObject(v)) {
1874                             $scope.working[k] = angular.copy(v);
1875                         } else {
1876                             angular.forEach(v, function (sv,sk) {
1877                                 if (!(k in $scope.working))
1878                                     $scope.working[k] = {};
1879                                 $scope.working[k][sk] = angular.copy(sv);
1880                             });
1881                         }
1882                     });
1883                     $scope.template_name = '';
1884                 }
1885
1886                 $scope.deleteTemplate = function (n) {
1887                     if (n) {
1888                         delete $scope.templates[n]
1889                         $scope.template_name_list = Object.keys($scope.templates);
1890                         $scope.template_name = '';
1891                         egCore.hatch.setItem('cat.copy.templates', $scope.templates);
1892                         $scope.$parent.fetchTemplates();
1893                         ngToast.create(egCore.strings.VOL_COPY_TEMPLATE_SUCCESS_DELETE);
1894                     }
1895                 }
1896
1897                 $scope.saveTemplate = function (n) {
1898                     if (n) {
1899                         var tmpl = {};
1900             
1901                         angular.forEach($scope.working, function (v,k) {
1902                             if (angular.isObject(v)) { // we'll use the pkey
1903                                 if (v.id) v = v.id();
1904                                 else if (v.code) v = v.code();
1905                             }
1906             
1907                             tmpl[k] = v;
1908                         });
1909             
1910                         $scope.templates[n] = tmpl;
1911                         $scope.template_name_list = Object.keys($scope.templates);
1912             
1913                         egCore.hatch.setItem('cat.copy.templates', $scope.templates);
1914                         $scope.$parent.fetchTemplates();
1915
1916                         $scope.dirty = false;
1917                     } else {
1918                         // save all templates, as we might do after an import
1919                         egCore.hatch.setItem('cat.copy.templates', $scope.templates);
1920                         $scope.$parent.fetchTemplates();
1921                     }
1922                     ngToast.create(egCore.strings.VOL_COPY_TEMPLATE_SUCCESS_SAVE);
1923                 }
1924             
1925                 $scope.templates = {};
1926                 $scope.imported_templates = { data : '' };
1927                 $scope.template_name = '';
1928                 $scope.template_name_list = [];
1929
1930                 $scope.$watch('imported_templates.data', function(newVal, oldVal) {
1931                     if (newVal && newVal != oldVal) {
1932                         try {
1933                             var newTemplates = JSON.parse(newVal);
1934                             if (!Object.keys(newTemplates).length) return;
1935                             $scope.templates = newTemplates;
1936                             $scope.template_name_list = Object.keys(newTemplates);
1937                             $scope.template_name = '';
1938                         } catch (E) {
1939                             console.log('tried to import an invalid copy template file');
1940                         }
1941                     }
1942                 });
1943
1944                 $scope.tracker = function (x,f) { if (x) return x[f]() };
1945                 $scope.idTracker = function (x) { if (x) return $scope.tracker(x,'id') };
1946                 $scope.cant_have_vols = function (id) { return !egCore.org.CanHaveVolumes(id); };
1947             
1948                 $scope.orgById = function (id) { return egCore.org.get(id) }
1949                 $scope.statusById = function (id) {
1950                     return $scope.status_list.filter( function (s) { return s.id() == id } )[0];
1951                 }
1952                 $scope.locationById = function (id) {
1953                     return $scope.location_cache[''+id];
1954                 }
1955             
1956                 createSimpleUpdateWatcher = function (field) {
1957                     $scope.$watch('working.' + field, function () {
1958                         var newval = $scope.working[field];
1959             
1960                         if (typeof newval != 'undefined') {
1961                             $scope.dirty = true;
1962                             if (angular.isObject(newval)) { // we'll use the pkey
1963                                 if (newval.id) $scope.working[field] = newval.id();
1964                                 else if (newval.code) $scope.working[field] = newval.code();
1965                             }
1966             
1967                             if (""+newval == "" || newval == null) {
1968                                 $scope.working[field] = undefined;
1969                             }
1970             
1971                         }
1972                     });
1973                 }
1974             
1975                 $scope.working = {
1976                     statcats: {},
1977                     statcat_filter: undefined
1978                 };
1979             
1980                 $scope.statcat_visible = function (sc_owner) {
1981                     var visible = typeof $scope.working.statcat_filter === 'undefined' || !$scope.working.statcat_filter;
1982                     angular.forEach(egCore.org.ancestors(sc_owner), function (ancestor_org) {
1983                         if ($scope.working.statcat_filter == ancestor_org.id())
1984                             visible = true;
1985                     });
1986                     return visible;
1987                 }
1988
1989                 createStatcatUpdateWatcher = function (id) {
1990                     return $scope.$watch('working.statcats[' + id + ']', function () {
1991                         if ($scope.working.statcats) {
1992                             var newval = $scope.working.statcats[id];
1993                 
1994                             if (typeof newval != 'undefined') {
1995                                 $scope.dirty = true;
1996                                 if (angular.isObject(newval)) { // we'll use the pkey
1997                                     newval = newval.id();
1998                                 }
1999                 
2000                                 if (""+newval == "" || newval == null) {
2001                                     $scope.working.statcats[id] = undefined;
2002                                     newval = null;
2003                                 }
2004                 
2005                             }
2006                         }
2007                     });
2008                 }
2009
2010                 $scope.clearWorking = function () {
2011                     angular.forEach($scope.working, function (v,k,o) {
2012                         if (!angular.isObject(v)) {
2013                             if (typeof v != 'undefined')
2014                                 $scope.working[k] = undefined;
2015                         } else if (k != 'circ_lib') {
2016                             angular.forEach(v, function (sv,sk) {
2017                                 $scope.working[k][sk] = undefined;
2018                             });
2019                         }
2020                     });
2021                     $scope.working.circ_lib = undefined; // special
2022                     $scope.dirty = false;
2023                 }
2024
2025                 $scope.working = {};
2026                 $scope.location_orgs = [];
2027                 $scope.location_cache = {};
2028             
2029                 $scope.location_list = [];
2030                 itemSvc.get_locations(
2031                     egCore.org.fullPath( egCore.auth.user().ws_ou(), true )
2032                 ).then(function(list){
2033                     $scope.location_list = list;
2034                 });
2035                 createSimpleUpdateWatcher('location');
2036
2037                 $scope.statcat_filter_list = egCore.org.fullPath( egCore.auth.user().ws_ou() );
2038
2039                 $scope.statcats = [];
2040                 itemSvc.get_statcats(
2041                     egCore.org.fullPath( egCore.auth.user().ws_ou(), true )
2042                 ).then(function(list){
2043                     $scope.statcats = list;
2044                     angular.forEach($scope.statcats, function (s) {
2045
2046                         if (!$scope.working)
2047                             $scope.working = { statcats: {}, statcat_filter: undefined};
2048                         if (!$scope.working.statcats)
2049                             $scope.working.statcats = {};
2050
2051                         $scope.working.statcats[s.id()] = undefined;
2052                         createStatcatUpdateWatcher(s.id());
2053                     });
2054                 });
2055             
2056                 $scope.status_list = [];
2057                 itemSvc.get_magic_statuses().then(function(list){
2058                     $scope.magic_status_list = list;
2059                 });
2060                 itemSvc.get_statuses().then(function(list){
2061                     $scope.status_list = list;
2062                 });
2063                 createSimpleUpdateWatcher('status');
2064             
2065                 $scope.circ_modifier_list = [];
2066                 itemSvc.get_circ_mods().then(function(list){
2067                     $scope.circ_modifier_list = list;
2068                 });
2069                 createSimpleUpdateWatcher('circ_modifier');
2070             
2071                 $scope.circ_type_list = [];
2072                 itemSvc.get_circ_types().then(function(list){
2073                     $scope.circ_type_list = list;
2074                 });
2075                 createSimpleUpdateWatcher('circ_as_type');
2076             
2077                 $scope.age_protect_list = [];
2078                 itemSvc.get_age_protects().then(function(list){
2079                     $scope.age_protect_list = list;
2080                 });
2081                 createSimpleUpdateWatcher('age_protect');
2082             
2083                 createSimpleUpdateWatcher('circulate');
2084                 createSimpleUpdateWatcher('holdable');
2085                 createSimpleUpdateWatcher('fine_level');
2086                 createSimpleUpdateWatcher('loan_duration');
2087                 createSimpleUpdateWatcher('cost');
2088                 createSimpleUpdateWatcher('deposit');
2089                 createSimpleUpdateWatcher('deposit_amount');
2090                 createSimpleUpdateWatcher('mint_condition');
2091                 createSimpleUpdateWatcher('opac_visible');
2092                 createSimpleUpdateWatcher('ref');
2093
2094                 $scope.suffix_list = [];
2095                 itemSvc.get_suffixes(egCore.auth.user().ws_ou()).then(function(list){
2096                     $scope.suffix_list = list;
2097                 });
2098
2099                 $scope.prefix_list = [];
2100                 itemSvc.get_prefixes(egCore.auth.user().ws_ou()).then(function(list){
2101                     $scope.prefix_list = list;
2102                 });
2103
2104                 $scope.classification_list = [];
2105                 itemSvc.get_classifications().then(function(list){
2106                     $scope.classification_list = list;
2107                 });
2108
2109                 createSimpleUpdateWatcher('working.callnumber.classification');
2110                 createSimpleUpdateWatcher('working.callnumber.prefix');
2111                 createSimpleUpdateWatcher('working.callnumber.suffix');
2112             }
2113         ]
2114     }
2115 })
2116
2117