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