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