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