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