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