]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/cat/volcopy/app.js
webstaff: teach volcopy editor how to be embeddable
[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(function($routeProvider, $locationProvider, $compileProvider) {
15     $locationProvider.html5Mode(true);
16     $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|blob):/); // grid export
17
18     var resolver = {
19         delay : ['egStartup', function(egStartup) { return egStartup.go(); }]
20     };
21
22     $routeProvider.when('/cat/volcopy/:dataKey', {
23         templateUrl: './cat/volcopy/t_view',
24         controller: 'EditCtrl',
25         resolve : resolver
26     });
27
28     $routeProvider.when('/cat/volcopy/:dataKey/:mode', {
29         templateUrl: './cat/volcopy/t_view',
30         controller: 'EditCtrl',
31         resolve : resolver
32     });
33 })
34
35 .factory('itemSvc', 
36        ['egCore','$q',
37 function(egCore , $q) {
38
39     var service = {
40         currently_generating : false,
41         auto_gen_barcode : false,
42         barcode_checkdigit : false,
43         new_cp_id : 0,
44         new_cn_id : 0,
45         tree : {}, // holds lib->cn->copy hash stack
46         copies : [] // raw copy list
47     };
48
49     service.nextBarcode = function(bc) {
50         service.currently_generating = true;
51         return egCore.net.request(
52             'open-ils.cat',
53             'open-ils.cat.item.barcode.autogen',
54             egCore.auth.token(),
55             bc, 1, { checkdigit: service.barcode_checkdigit }
56         ).then(function(resp) { // get_barcodes
57             var evt = egCore.evt.parse(resp);
58             if (!evt) return resp[0];
59             return '';
60         });
61     };
62
63     service.checkBarcode = function(bc) {
64         if (!service.barcode_checkdigit) return true;
65         if (bc != Number(bc)) return false;
66         bc = bc.toString();
67         // "16.00" == Number("16.00"), but the . is bad.
68         // Throw out any barcode that isn't just digits
69         if (bc.search(/\D/) != -1) return false;
70         var last_digit = bc.substr(bc.length-1);
71         var stripped_barcode = bc.substr(0,bc.length-1);
72         return service.barcodeCheckdigit(stripped_barcode).toString() == last_digit;
73     };
74
75     service.barcodeCheckdigit = function(bc) {
76         var reverse_barcode = bc.toString().split('').reverse();
77         var check_sum = 0; var multiplier = 2;
78         for (var i = 0; i < reverse_barcode.length; i++) {
79             var digit = reverse_barcode[i];
80             var product = digit * multiplier; product = product.toString();
81             var temp_sum = 0;
82             for (var j = 0; j < product.length; j++) {
83                 temp_sum += Number( product[j] );
84             }
85             check_sum += Number( temp_sum );
86             multiplier = ( multiplier == 2 ? 1 : 2 );
87         }
88         check_sum = check_sum.toString();
89         var next_multiple_of_10 = (check_sum.match(/(\d*)\d$/)[1] * 10) + 10;
90         var check_digit = next_multiple_of_10 - Number(check_sum); if (check_digit == 10) check_digit = 0;
91         return check_digit;
92     };
93
94     // returns a promise resolved with the list of circ mods
95     service.get_classifications = function() {
96         if (egCore.env.acnc)
97             return $q.when(egCore.env.acnc.list);
98
99         return egCore.pcrud.retrieveAll('acnc', null, {atomic : true})
100         .then(function(list) {
101             egCore.env.absorbList(list, 'acnc');
102             return list;
103         });
104     };
105
106     service.get_prefixes = function(org) {
107         return egCore.pcrud.search('acnp',
108             {owning_lib : egCore.org.fullPath(org, true)},
109             null, {atomic : true}
110         );
111
112     };
113
114     service.get_statcats = function(orgs) {
115         return egCore.pcrud.search('asc',
116             {owner : orgs},
117             { flesh : 1,
118               flesh_fields : {
119                 asc : ['owner','entries']
120               }
121             },
122             { atomic : true }
123         );
124     };
125
126     service.get_locations = function(orgs) {
127         return egCore.pcrud.search('acpl',
128             {owning_lib : orgs},
129             null, {atomic : true}
130         );
131     };
132
133     service.get_suffixes = function(org) {
134         return egCore.pcrud.search('acns',
135             {owning_lib : egCore.org.fullPath(org, true)},
136             null, {atomic : true}
137         );
138
139     };
140
141     service.get_statuses = function() {
142         if (egCore.env.ccs)
143             return $q.when(egCore.env.ccs.list);
144
145         return egCore.pcrud.retrieveAll('ccs', {}, {atomic : true}).then(
146             function(list) {
147                 egCore.env.absorbList(list, 'ccs');
148                 return list;
149             }
150         );
151
152     };
153
154     service.get_circ_mods = function() {
155         if (egCore.env.ccm)
156             return $q.when(egCore.env.ccm.list);
157
158         return egCore.pcrud.retrieveAll('ccm', {}, {atomic : true}).then(
159             function(list) {
160                 egCore.env.absorbList(list, 'ccm');
161                 return list;
162             }
163         );
164
165     };
166
167     service.get_circ_types = function() {
168         if (egCore.env.citm)
169             return $q.when(egCore.env.citm.list);
170
171         return egCore.pcrud.retrieveAll('citm', {}, {atomic : true}).then(
172             function(list) {
173                 egCore.env.absorbList(list, 'citm');
174                 return list;
175             }
176         );
177
178     };
179
180     service.get_age_protects = function() {
181         if (egCore.env.crahp)
182             return $q.when(egCore.env.crahp.list);
183
184         return egCore.pcrud.retrieveAll('crahp', {}, {atomic : true}).then(
185             function(list) {
186                 egCore.env.absorbList(list, 'crahp');
187                 return list;
188             }
189         );
190
191     };
192
193     service.bmp_parts = {};
194     service.get_parts = function(rec) {
195         if (service.bmp_parts[rec])
196             return $q.when(service.bmp_parts[rec]);
197
198         return egCore.pcrud.search('bmp',
199             {record : rec, deleted : 'f'},
200             null, {atomic : true}
201         ).then(function(list) {
202             service.bmp_parts[rec] = list;
203             return list;
204         });
205
206     };
207
208     service.flesh = {   
209         flesh : 3, 
210         flesh_fields : {
211             acp : ['call_number','parts','stat_cat_entries', 'notes'],
212             acn : ['label_class','prefix','suffix']
213         }
214     }
215
216     service.addCopy = function (cp) {
217
218         if (!cp.parts()) cp.parts([]); // just in case...
219
220         var lib = cp.call_number().owning_lib();
221         var cn = cp.call_number().id();
222
223         if (!service.tree[lib]) service.tree[lib] = {};
224         if (!service.tree[lib][cn]) service.tree[lib][cn] = [];
225
226         service.tree[lib][cn].push(cp);
227         service.copies.push(cp);
228     }
229
230     service.fetchIds = function(idList) {
231         service.tree = {}; // clear the tree on fetch
232         service.copies = []; // clear the copy list on fetch
233         return egCore.pcrud.search('acp', { 'id' : idList }, service.flesh).then(null,null,
234             function(copy) {
235                 service.addCopy(copy);
236             }
237         );
238     }
239
240     return service;
241 }])
242
243 .directive("egVolCopyEdit", function () {
244     return {
245         restrict: 'E',
246         replace: true,
247         template:
248             '<div class="row">'+
249                 '<div class="col-xs-5" ng-class="{'+"'has-error'"+':barcode_has_error}">'+
250                     '<input id="{{callNumber.id()}}_{{copy.id()}}"'+
251                     ' eg-enter="nextBarcode(copy.id())" class="form-control"'+
252                     ' type="text" ng-model="barcode" ng-change="updateBarcode()"/>'+
253                 '</div>'+
254                 '<div class="col-xs-3"><input class="form-control" type="number" ng-model="copy_number" ng-change="updateCopyNo()"/></div>'+
255                 '<div class="col-xs-4"><eg-basic-combo-box list="parts" selected="part"></eg-basic-combo-box></div>'+
256             '</div>',
257
258         scope: { focusNext: "=", copy: "=", callNumber: "=", index: "@" },
259         controller : ['$scope','itemSvc','egCore',
260             function ( $scope , itemSvc , egCore ) {
261                 $scope.new_part_id = 0;
262                 $scope.barcode_has_error = false;
263
264                 $scope.nextBarcode = function (i) {
265                     $scope.focusNext(i, $scope.barcode);
266                 }
267
268                 $scope.updateBarcode = function () {
269                     if ($scope.barcode != '')
270                         $scope.barcode_has_error = !Boolean(itemSvc.checkBarcode($scope.barcode));
271                     $scope.copy.barcode($scope.barcode);
272                     $scope.copy.ischanged(1);
273                     if (itemSvc.currently_generating)
274                         $scope.focusNext($scope.copy.id(), $scope.barcode);
275                 };
276
277                 $scope.updateCopyNo = function () { $scope.copy.copy_number($scope.copy_number); $scope.copy.ischanged(1); };
278                 $scope.updatePart = function () {
279                     if ($scope.part) {
280                         var p = $scope.part_list.filter(function (x) {
281                             return x.label() == $scope.part
282                         });
283                         if (p.length > 0) { // preexisting part
284                             $scope.copy.parts(p)
285                         } else { // create one...
286                             var part = new egCore.idl.bmp();
287                             part.id( --$scope.new_part_id );
288                             part.isnew( true );
289                             part.label( $scope.part );
290                             part.record( $scope.callNumber.record() );
291                             $scope.copy.parts([part]);
292                             $scope.copy.ischanged(1);
293                         }
294                     } else {
295                         $scope.copy.parts([]);
296                     }
297                 }
298                 $scope.$watch('part', $scope.updatePart);
299
300                 $scope.barcode = $scope.copy.barcode();
301                 $scope.copy_number = $scope.copy.copy_number();
302
303                 if ($scope.copy.parts()) {
304                     $scope.part = $scope.copy.parts()[0];
305                     if ($scope.part) $scope.part = $scope.part.label();
306                 };
307
308                 $scope.parts = [];
309                 $scope.part_list = [];
310
311                 itemSvc.get_parts($scope.callNumber.record()).then(function(list){
312                     $scope.part_list = list;
313                     angular.forEach(list, function(p){ $scope.parts.push(p.label()) });
314                     $scope.parts = angular.copy($scope.parts);
315                 });
316
317             }
318         ]
319
320     }
321 })
322
323 .directive("egVolRow", function () {
324     return {
325         restrict: 'E',
326         replace: true,
327         transclude: true,
328         template:
329             '<div class="row">'+
330                 '<div class="col-xs-2">'+
331                     '<select class="form-control" ng-model="classification" ng-change="updateClassification()" ng-options="cl.name() for cl in classification_list"/>'+
332                 '</div>'+
333                 '<div class="col-xs-1">'+
334                     '<select class="form-control" ng-model="prefix" ng-change="updatePrefix()" ng-options="p.label() for p in prefix_list"/>'+
335                 '</div>'+
336                 '<div class="col-xs-2"><input class="form-control" type="text" ng-change="updateLabel()" ng-model="label"/></div>'+
337                 '<div class="col-xs-1">'+
338                     '<select class="form-control" ng-model="suffix" ng-change="updateSuffix()" ng-options="s.label() for s in suffix_list"/>'+
339                 '</div>'+
340                 '<div ng-hide="onlyVols" class="col-xs-1"><input class="form-control" type="number" ng-model="copy_count" min="{{orig_copy_count}}" ng-change="changeCPCount()"></div>'+
341                 '<div ng-hide="onlyVols" class="col-xs-5">'+
342                     '<eg-vol-copy-edit ng-repeat="cp in copies track by idTracker(cp)" focus-next="focusNextBarcode" copy="cp" call-number="callNumber"></eg-vol-copy-edit>'+
343                 '</div>'+
344             '</div>',
345
346         scope: {focusNext: "=", allcopies: "=", copies: "=", onlyVols: "=" },
347         controller : ['$scope','itemSvc','egCore',
348             function ( $scope , itemSvc , egCore ) {
349                 $scope.callNumber =  $scope.copies[0].call_number();
350
351                 $scope.idTracker = function (x) { if (x && x.id) return x.id() };
352
353                 // XXX $() is not working! arg
354                 $scope.focusNextBarcode = function (i, prev_bc) {
355                     var n;
356                     var yep = false;
357                     angular.forEach($scope.copies, function (cp) {
358                         if (n) return;
359
360                         if (cp.id() == i) {
361                             yep = true;
362                             return;
363                         }
364
365                         if (yep) n = cp.id();
366                     });
367
368                     if (n) {
369                         var next = '#' + $scope.callNumber.id() + '_' + n;
370                         var el = $(next);
371                         if (el) {
372                             if (!itemSvc.currently_generating) el.focus();
373                             if (prev_bc && itemSvc.auto_gen_barcode && el.val() == "") {
374                                 itemSvc.nextBarcode(prev_bc).then(function(bc){
375                                     el.focus();
376                                     el.val(bc);
377                                     el.trigger('change');
378                                 });
379                             } else {
380                                 itemSvc.currently_generating = false;
381                             }
382                         }
383                     } else {
384                         $scope.focusNext($scope.callNumber.id(),prev_bc)
385                     }
386                 }
387
388                 $scope.suffix_list = [];
389                 itemSvc.get_suffixes($scope.callNumber.owning_lib()).then(function(list){
390                     $scope.suffix_list = list;
391                     $scope.$watch('callNumber.suffix()', function (v) {
392                         if (angular.isObject(v)) v = v.id();
393                         $scope.suffix = $scope.suffix_list.filter( function (s) {
394                             return s.id() == v;
395                         })[0];
396                     });
397
398                 });
399                 $scope.updateSuffix = function () {
400                     angular.forEach($scope.copies, function(cp) {
401                         cp.call_number().suffix($scope.suffix);
402                         cp.call_number().ischanged(1);
403                     });
404                 }
405
406                 $scope.prefix_list = [];
407                 itemSvc.get_prefixes($scope.callNumber.owning_lib()).then(function(list){
408                     $scope.prefix_list = list;
409                     $scope.$watch('callNumber.prefix()', function (v) {
410                         if (angular.isObject(v)) v = v.id();
411                         $scope.prefix = $scope.prefix_list.filter(function (p) {
412                             return p.id() == v;
413                         })[0];
414                     });
415
416                 });
417                 $scope.updatePrefix = function () {
418                     angular.forEach($scope.copies, function(cp) {
419                         cp.call_number().prefix($scope.prefix);
420                         cp.call_number().ischanged(1);
421                     });
422                 }
423
424                 $scope.classification_list = [];
425                 itemSvc.get_classifications().then(function(list){
426                     $scope.classification_list = list;
427                     $scope.$watch('callNumber.label_class()', function (v) {
428                         if (angular.isObject(v)) v = v.id();
429                         $scope.classification = $scope.classification_list.filter(function (c) {
430                             return c.id() == v;
431                         })[0];
432                     });
433
434                 });
435                 $scope.updateClassification = function () {
436                     angular.forEach($scope.copies, function(cp) {
437                         cp.call_number().label_class($scope.classification);
438                         cp.call_number().ischanged(1);
439                     });
440                 }
441
442                 $scope.updateLabel = function () {
443                     angular.forEach($scope.copies, function(cp) {
444                         cp.call_number().label($scope.label);
445                         cp.call_number().ischanged(1);
446                     });
447                 }
448
449                 $scope.$watch('callNumber.label()', function (v) {
450                     $scope.label = v;
451                 });
452
453                 $scope.prefix = $scope.callNumber.prefix();
454                 $scope.suffix = $scope.callNumber.suffix();
455                 $scope.classification = $scope.callNumber.label_class();
456                 $scope.label = $scope.callNumber.label();
457
458                 $scope.copy_count = $scope.copies.length;
459                 $scope.orig_copy_count = $scope.copy_count;
460
461                 $scope.changeCPCount = function () {
462                     while ($scope.copy_count > $scope.copies.length) {
463                         var cp = new egCore.idl.acp();
464                         cp.id( --itemSvc.new_cp_id );
465                         cp.isnew( true );
466                         cp.circ_lib( $scope.lib );
467                         cp.call_number( $scope.callNumber );
468                         $scope.copies.push( cp );
469                         $scope.allcopies.push( cp );
470                     }
471
472                     if ($scope.copy_count >= $scope.orig_copy_count) {
473                         var how_many = $scope.copies.length - $scope.copy_count;
474                         if (how_many > 0) {
475                             var dead = $scope.copies.splice($scope.copy_count,how_many);
476                             $scope.callNumber.copies($scope.copies);
477
478                             // Trimming the global list is a bit more tricky
479                             angular.forEach( dead, function (d) {
480                                 angular.forEach( $scope.allcopies, function (l, i) { 
481                                     if (l === d) $scope.allcopies.splice(i,1);
482                                 });
483                             });
484                         }
485                     }
486                 }
487
488             }
489         ]
490
491     }
492 })
493
494 .directive("egVolEdit", function () {
495     return {
496         restrict: 'E',
497         replace: true,
498         template:
499             '<div class="row">'+
500                 '<div class="col-xs-1"><eg-org-selector selected="owning_lib" disableTest="cant_have_vols"></eg-org-selector></div>'+
501                 '<div class="col-xs-1"><input class="form-control" type="number" min="{{orig_cn_count}}" ng-model="cn_count" ng-change="changeCNCount()"/></div>'+
502                 '<div class="col-xs-10">'+
503                     '<eg-vol-row only-vols="onlyVols"'+
504                         'ng-repeat="(cn,copies) in struct | orderBy:cn track by cn" '+
505                         'focus-next="focusNextFirst" copies="copies" allcopies="allcopies">'+
506                     '</eg-vol-row>'+
507                 '</div>'+
508             '</div>',
509
510         scope: { focusNext: "=", allcopies: "=", struct: "=", lib: "@", record: "@", onlyVols: "=" },
511         controller : ['$scope','itemSvc','egCore',
512             function ( $scope , itemSvc , egCore ) {
513                 $scope.first_cn = Object.keys($scope.struct)[0];
514                 $scope.full_cn = $scope.struct[$scope.first_cn][0].call_number();
515
516                 $scope.defaults = {};
517                 egCore.hatch.getItem('cat.copy.defaults').then(function(t) {
518                     if (t) {
519                         $scope.defaults = t;
520                     }
521                 });
522
523                 $scope.focusNextFirst = function(prev_cn,prev_bc) {
524                     var n;
525                     var yep = false;
526                     angular.forEach(Object.keys($scope.struct).sort(), function (cn) {
527                         if (n) return;
528
529                         if (cn == prev_cn) {
530                             yep = true;
531                             return;
532                         }
533
534                         if (yep) n = cn;
535                     });
536
537                     if (n) {
538                         var next = '#' + n + '_' + $scope.struct[n][0].id();
539                         var el = $(next);
540                         if (el) {
541                             if (!itemSvc.currently_generating) el.focus();
542                             if (prev_bc && itemSvc.auto_gen_barcode && el.val() == "") {
543                                 itemSvc.nextBarcode(prev_bc).then(function(bc){
544                                     el.focus();
545                                     el.val(bc);
546                                     el.trigger('change');
547                                 });
548                             } else {
549                                 itemSvc.currently_generating = false;
550                             }
551                         }
552                     } else {
553                         $scope.focusNext($scope.lib, prev_bc);
554                     }
555                 }
556
557                 $scope.cn_count = Object.keys($scope.struct).length;
558                 $scope.orig_cn_count = $scope.cn_count;
559
560                 $scope.owning_lib = egCore.org.get($scope.lib);
561                 $scope.$watch('owning_lib', function (l) {
562                     angular.forEach( $scope.struct[$scope.first_cn], function (cp) {
563                         cp.call_number().owning_lib( $scope.owning_lib.id() );
564                     });
565                 });
566
567                 $scope.cant_have_vols = function (id) { return !egCore.org.CanHaveVolumes(id); };
568
569                 $scope.$watch('cn_count', function (n) {
570                     var o = Object.keys($scope.struct).length;
571                     if (n > o) { // adding
572                         for (var i = o; o < n; o++) {
573                             var cn = new egCore.idl.acn();
574                             cn.id( --itemSvc.new_cn_id );
575                             cn.isnew( true );
576                             cn.prefix( $scope.defaults.prefix || -1 );
577                             cn.suffix( $scope.defaults.suffix || -1 );
578                             cn.label_class( $scope.defaults.classification || 1 );
579                             cn.owning_lib( $scope.owning_lib.id() );
580                             cn.record( $scope.full_cn.record() );
581
582                             var cp = new egCore.idl.acp();
583                             cp.call_number( cn );
584                             cp.id( --itemSvc.new_cp_id );
585                             cp.isnew( true );
586
587                             cp.deposit(0);
588                             cp.price(0);
589                             cp.deposit_amount(0);
590                             cp.fine_level(2); // Normal
591                             cp.loan_duration(2); // Normal
592                             cp.location(1); // Stacks
593                             cp.circulate('t');
594                             cp.holdable('t');
595                             cp.opac_visible('t');
596                             cp.ref('f');
597                             cp.mint_condition('t');
598
599                             cp.circ_lib( $scope.owning_lib.id() );
600                             cp.call_number( cn );
601
602                             $scope.struct[cn.id()] = [cp];
603                             $scope.allcopies.push(cp);
604                         }
605                     } else if (n < o && n >= $scope.orig_cn_count) { // removing
606                         var how_many = o - n;
607                         var list = Object
608                                 .keys($scope.struct)
609                                 .sort(function(a, b){return parseInt(a)-parseInt(b)})
610                                 .filter(function(x){ return parseInt(x) <= 0 });
611                         for (var i = 0; i < how_many; i++) {
612                             // Trimming the global list is a bit more tricky
613                             angular.forEach($scope.struct[list[i]], function (d) {
614                                 angular.forEach( $scope.allcopies, function (l, j) { 
615                                     if (l === d) $scope.allcopies.splice(j,1);
616                                 });
617                             });
618                             delete $scope.struct[list[i]];
619                         }
620                     }
621                 });
622             }
623         ]
624
625     }
626 })
627
628 /**
629  * Edit controller!
630  */
631 .controller('EditCtrl', 
632        ['$scope','$q','$window','$routeParams','$location','$timeout','egCore','egNet','egGridDataProvider','itemSvc','$modal',
633 function($scope , $q , $window , $routeParams , $location , $timeout , egCore , egNet , egGridDataProvider , itemSvc , $modal) {
634
635     $scope.defaults = { // If defaults are not set at all, allow everything
636         barcode_checkdigit : false,
637         auto_gen_barcode : false,
638         statcats : true,
639         copy_notes : true,
640         attributes : {
641             status : true,
642             loan_duration : true,
643             fine_level : true,
644             cost : true,
645             alerts : true,
646             deposit : true,
647             deposit_amount : true,
648             opac_visible : true,
649             price : true,
650             circulate : true,
651             mint_condition : true,
652             circ_lib : true,
653             ref : true,
654             circ_modifier : true,
655             circ_as_type : true,
656             location : true,
657             holdable : true,
658             age_protect : true
659         }
660     };
661
662     $scope.embedded = ($routeParams.mode && $routeParams.mode == 'embedded') ? true : false;
663
664     $scope.saveDefaults = function () {
665         egCore.hatch.setItem('cat.copy.defaults', $scope.defaults);
666     }
667
668     $scope.fetchDefaults = function () {
669         egCore.hatch.getItem('cat.copy.defaults').then(function(t) {
670             if (t) {
671                 $scope.defaults = t;
672                 if (!$scope.batch) $scope.batch = {};
673                 $scope.batch.classification = $scope.defaults.classification;
674                 $scope.batch.prefix = $scope.defaults.prefix;
675                 $scope.batch.suffix = $scope.defaults.suffix;
676                 $scope.working.statcat_filter = $scope.defaults.statcat_filter;
677                 if ($scope.defaults.always_vols) $scope.show_vols = true;
678                 if ($scope.defaults.barcode_checkdigit) itemSvc.barcode_checkdigit = true;
679                 if ($scope.defaults.auto_gen_barcode) itemSvc.auto_gen_barcode = true;
680             }
681         });
682     }
683     $scope.fetchDefaults();
684
685     $scope.$watch('defaults.auto_gen_barcode', function (n,o) {
686         itemSvc.auto_gen_barcode = n
687     });
688
689     $scope.$watch('defaults.barcode_checkdigit', function (n,o) {
690         itemSvc.barcode_checkdigit = n
691     });
692
693     $scope.dirty = false;
694     $scope.$watch('dirty',
695         function(newVal, oldVal) {
696             if (newVal && newVal != oldVal) {
697                 $($window).on('beforeunload.edit', function(){
698                     return 'There is unsaved data!'
699                 });
700             } else {
701                 $($window).off('beforeunload.edit');
702             }
703         }
704     );
705
706     $scope.only_vols = false;
707     $scope.show_vols = true;
708     $scope.show_copies = true;
709
710     $scope.tracker = function (x,f) { if (x) return x[f]() };
711     $scope.idTracker = function (x) { if (x) return $scope.tracker(x,'id') };
712     $scope.cant_have_vols = function (id) { return !egCore.org.CanHaveVolumes(id); };
713
714     $scope.orgById = function (id) { return egCore.org.get(id) }
715     $scope.statusById = function (id) {
716         return $scope.status_list.filter( function (s) { return s.id() == id } )[0];
717     }
718     $scope.locationById = function (id) {
719         return $scope.location_cache[''+id];
720     }
721
722     $scope.workingToComplete = function () {
723         angular.forEach( $scope.workingGridControls.selectedItems(), function (c) {
724             angular.forEach( itemSvc.copies, function (w, i) {
725                 if (c === w)
726                     $scope.completed_copies = $scope.completed_copies.concat(itemSvc.copies.splice(i,1));
727             });
728         });
729
730         return true;
731     }
732
733     $scope.completeToWorking = function () {
734         angular.forEach( $scope.completedGridControls.selectedItems(), function (c) {
735             angular.forEach( $scope.completed_copies, function (w, i) {
736                 if (c === w)
737                     itemSvc.copies = itemSvc.copies.concat($scope.completed_copies.splice(i,1));
738             });
739         });
740
741         return true;
742     }
743
744     createSimpleUpdateWatcher = function (field) {
745         return $scope.$watch('working.' + field, function () {
746             var newval = $scope.working[field];
747
748             if (typeof newval != 'undefined') {
749                 if (angular.isObject(newval)) { // we'll use the pkey
750                     if (newval.id) newval = newval.id();
751                     else if (newval.code) newval = newval.code();
752                 }
753
754                 if (""+newval == "" || newval == null) {
755                     $scope.working[field] = undefined;
756                     newval = null;
757                 }
758
759                 if ($scope.workingGridControls && $scope.workingGridControls.selectedItems) {
760                     angular.forEach(
761                         $scope.workingGridControls.selectedItems(),
762                         function (cp) {
763                             if (cp[field]() !== newval) {
764                                 cp[field](newval);
765                                 cp.ischanged(1);
766                                 $scope.dirty = true;
767                             }
768                         }
769                     );
770                 }
771             }
772         });
773     }
774
775     $scope.working = {
776         statcats: {},
777         statcat_filter: undefined
778     };
779
780     $scope.statcatUpdate = function (id) {
781         var newval = $scope.working.statcats[id];
782
783         if (typeof newval != 'undefined') {
784             if (angular.isObject(newval)) { // we'll use the pkey
785                 newval = newval.id();
786             }
787     
788             if (""+newval == "" || newval == null) {
789                 $scope.working.statcats[id] = undefined;
790                 newval = null;
791             }
792     
793             if (!$scope.in_item_select && $scope.workingGridControls && $scope.workingGridControls.selectedItems) {
794                 angular.forEach(
795                     $scope.workingGridControls.selectedItems(),
796                     function (cp) {
797                         $scope.dirty = true;
798
799                         cp.stat_cat_entries(
800                             angular.forEach( cp.stat_cat_entries(), function (e) {
801                                 if (e.stat_cat() == id) { // mark deleted
802                                     e.isdeleted(1);
803                                 }
804                             })
805                         );
806     
807                         if (newval) {
808                             var e = new egCore.idl.ascecm();
809                             e.isnew( 1 );
810                             e.owning_copy( cp.id() );
811                             e.stat_cat( id );
812                             e.stat_cat_entry( newval );
813
814                             cp.stat_cat_entries(
815                                 cp.stat_cat_entries().concat([ e ])
816                             );
817
818                         }
819
820                         cp.stat_cat_entries( // trim out ephemeral deleted ones
821                             cp.stat_cat_entries().filter(function (e) {
822                                 if (Boolean(e.isnew())) {
823                                     if (Boolean(e.isdeleted())) {
824                                         return false;
825                                     }
826                                 }
827                                 return true;
828                             })
829                         );
830    
831                         cp.ischanged(1);
832                     }
833                 );
834             }
835         }
836     }
837
838     var dataKey = $routeParams.dataKey;
839     console.debug('dataKey: ' + dataKey);
840
841     if (dataKey && dataKey.length > 0) {
842
843         $scope.templates = {};
844         $scope.template_name = '';
845         $scope.template_name_list = [];
846
847         $scope.fetchTemplates = function () {
848             egCore.hatch.getItem('cat.copy.templates').then(function(t) {
849                 if (t) {
850                     $scope.templates = t;
851                     $scope.template_name_list = Object.keys(t);
852                 }
853             });
854             egCore.hatch.getItem('cat.copy.last_template').then(function(t) {
855                 if (t) $scope.template_name = t;
856             });
857         }
858         $scope.fetchTemplates();
859
860         $scope.applyTemplate = function (n) {
861             angular.forEach($scope.templates[n], function (v,k) {
862                 if (k == 'circ_lib') {
863                     $scope.working[k] = egCore.org.get(v);
864                 } else if (!angular.isObject(v)) {
865                     $scope.working[k] = angular.copy(v);
866                 } else {
867                     angular.forEach(v, function (sv,sk) {
868                         if (k == 'callnumber') {
869                             angular.forEach(v, function (cnv,cnk) {
870                                 $scope.batch[cnk] = cnv;
871                             });
872                             $scope.applyBatchCNValues();
873                         } else {
874                             $scope.working[k][sk] = angular.copy(sv);
875                             if (k == 'statcats') $scope.statcatUpdate(sk);
876                         }
877                     });
878                 }
879             });
880             egCore.hatch.setItem('cat.copy.last_template', n);
881         }
882
883         $scope.copytab = 'working';
884         $scope.tab = 'edit';
885         $scope.summaryRecord = null;
886         $scope.record_id = null;
887         $scope.data = {};
888         $scope.completed_copies = [];
889         $scope.location_orgs = [];
890         $scope.location_cache = {};
891         $scope.statcats = [];
892         if (!$scope.batch) $scope.batch = {};
893
894         $scope.applyBatchCNValues = function () {
895             if ($scope.data.tree) {
896                 angular.forEach($scope.data.tree, function(cn_hash) {
897                     angular.forEach(cn_hash, function(copies) {
898                         angular.forEach(copies, function(cp) {
899                             if (typeof $scope.batch.classification != 'undefined' && $scope.batch.classification != '') {
900                                 var label_class = $scope.classification_list.filter(function(p){ return p.id() == $scope.batch.classification })[0];
901                                 cp.call_number().label_class(label_class);
902                                 cp.call_number().ischanged(1);
903                                 $scope.dirty = true;
904                             }
905                             if (typeof $scope.batch.prefix != 'undefined' && $scope.batch.prefix != '') {
906                                 var prefix = $scope.prefix_list.filter(function(p){ return p.id() == $scope.batch.prefix })[0];
907                                 cp.call_number().prefix(prefix);
908                                 cp.call_number().ischanged(1);
909                                 $scope.dirty = true;
910                             }
911                             if (typeof $scope.batch.label != 'undefined' && $scope.batch.label != '') {
912                                 cp.call_number().label($scope.batch.label);
913                                 cp.call_number().ischanged(1);
914                                 $scope.dirty = true;
915                             }
916                             if (typeof $scope.batch.suffix != 'undefined' && $scope.batch.suffix != '') {
917                                 var suffix = $scope.suffix_list.filter(function(p){ return p.id() == $scope.batch.suffix })[0];
918                                 cp.call_number().suffix(suffix);
919                                 cp.call_number().ischanged(1);
920                                 $scope.dirty = true;
921                             }
922                         });
923                     });
924                 });
925             }
926         }
927
928         $scope.clearWorking = function () {
929             angular.forEach($scope.working, function (v,k,o) {
930                 if (!angular.isObject(v)) {
931                     if (typeof v != 'undefined')
932                         $scope.working[k] = undefined;
933                 } else if (k != 'circ_lib') {
934                     angular.forEach(v, function (sv,sk) {
935                         if (typeof v != 'undefined')
936                             $scope.working[k][sk] = undefined;
937                     });
938                 }
939             });
940             $scope.working.circ_lib = undefined; // special
941         }
942
943         $scope.completedGridDataProvider = egGridDataProvider.instance({
944             get : function(offset, count) {
945                 //return provider.arrayNotifier(itemSvc.copies, offset, count);
946                 return this.arrayNotifier($scope.completed_copies, offset, count);
947             }
948         });
949
950         $scope.completedGridControls = {};
951
952         $scope.workingGridDataProvider = egGridDataProvider.instance({
953             get : function(offset, count) {
954                 //return provider.arrayNotifier(itemSvc.copies, offset, count);
955                 return this.arrayNotifier(itemSvc.copies, offset, count);
956             }
957         });
958
959         $scope.workingGridControls = {};
960         $scope.add_vols_copies = false;
961
962         egNet.request(
963             'open-ils.actor',
964             'open-ils.actor.anon_cache.get_value',
965             dataKey, 'edit-these-copies'
966         ).then(function (data) {
967
968             if (data) {
969                 if (data.hide_vols && !$scope.defaults.always_vols) $scope.show_vols = false;
970                 if (data.hide_copies) {
971                     $scope.show_copies = false;
972                     $scope.only_vols = true;
973                 }
974
975                 $scope.record_id = data.record_id;
976
977                 if (data.copies && data.copies.length)
978                     return itemSvc.fetchIds(data.copies);
979
980                 if (data.raw && data.raw.length) {
981                     $scope.dirty = true;
982                     $scope.add_vols_copies = true;
983
984                     /* data.raw data structure looks like this:
985                      * [{
986                      *      callnumber : $cn_id, // optional, to add a copy to a cn
987                      *      owner      : $org, // optional, defaults to ws_ou
988                      *      label      : $cn_label, // optional, to supply a label on a new cn
989                      *      barcode    : $cp_barcode // optional, to supply a barcode on a new cp
990                      * },...]
991                      * 
992                      * All can be left out and a completely empty vol/copy combo will be vivicated.
993                      */
994
995                     angular.forEach(
996                         data.raw,
997                         function (proto) {
998                             if (proto.callnumber) {
999                                 return egCore.pcrud.retrieve('acn', proto.callnumber)
1000                                 .then(function(cn) {
1001                                     var cp = new egCore.idl.acp();
1002                                     cp.call_number( cn );
1003                                     cp.id( --itemSvc.new_cp_id );
1004                                     cp.isnew( true );
1005                                     cp.circ_lib( proto.owner || egCore.auth.user().ws_ou() );
1006
1007                                     cp.deposit(0);
1008                                     cp.price(0);
1009                                     cp.deposit_amount(0);
1010                                     cp.fine_level(2); // Normal
1011                                     cp.loan_duration(2); // Normal
1012                                     cp.location(1); // Stacks
1013                                     cp.circulate('t');
1014                                     cp.holdable('t');
1015                                     cp.opac_visible('t');
1016                                     cp.ref('f');
1017                                     cp.mint_condition('t');
1018
1019                                     if (proto.barcode) cp.barcode( proto.barcode );
1020
1021                                     itemSvc.addCopy(cp)
1022                                 });
1023                             } else {
1024                                 var cn = new egCore.idl.acn();
1025                                 cn.id( --itemSvc.new_cn_id );
1026                                 cn.isnew( true );
1027                                 cn.prefix( $scope.defaults.prefix || -1 );
1028                                 cn.suffix( $scope.defaults.suffix || -1 );
1029                                 cn.label_class( $scope.defaults.classification || 1 );
1030                                 cn.owning_lib( proto.owner || egCore.auth.user().ws_ou() );
1031                                 cn.record( $scope.record_id );
1032                                 if (proto.label) cn.label( proto.label );
1033
1034                                 var cp = new egCore.idl.acp();
1035                                 cp.call_number( cn );
1036                                 cp.id( --itemSvc.new_cp_id );
1037                                 cp.isnew( true );
1038
1039                                 cp.deposit(0);
1040                                 cp.price(0);
1041                                 cp.deposit_amount(0);
1042                                 cp.fine_level(2); // Normal
1043                                 cp.loan_duration(2); // Normal
1044                                 cp.location(1); // Stacks
1045                                 cp.circulate('t');
1046                                 cp.holdable('t');
1047                                 cp.opac_visible('t');
1048                                 cp.ref('f');
1049                                 cp.mint_condition('t');
1050
1051                                 cp.circ_lib( proto.owner || egCore.auth.user().ws_ou() );
1052                                 if (proto.barcode) cp.barcode( proto.barcode );
1053
1054                                 itemSvc.addCopy(cp)
1055                             }
1056     
1057                         }
1058                     );
1059
1060                     return itemSvc.copies;
1061                 }
1062             }
1063
1064         }).then( function() {
1065             $scope.data = itemSvc;
1066             if ($scope.add_vols_copies) {
1067                 egCore.org.settings([
1068                     'cat.default_copy_status_fast'
1069                 ]).then(function(set) {
1070                     $scope.fast_ccs = set['cat.default_copy_status_fast'] || 0;
1071                     angular.forEach($scope.data.copies, function (cp) {
1072                         cp.status($scope.fast_ccs);
1073                     });
1074                     $scope.workingGridDataProvider.refresh();
1075                 });
1076             }
1077         });
1078
1079         $scope.focusNextFirst = function(prev_lib,prev_bc) {
1080             var n;
1081             var yep = false;
1082             angular.forEach(Object.keys($scope.data.tree).sort(), function (lib) {
1083                 if (n) return;
1084
1085                 if (lib == prev_lib) {
1086                     yep = true;
1087                     return;
1088                 }
1089
1090                 if (yep) n = lib;
1091             });
1092
1093             if (n) {
1094                 var first_cn = Object.keys($scope.data.tree[n])[0];
1095                 var next = '#' + first_cn + '_' + $scope.data.tree[n][first_cn][0].id();
1096                 var el = $(next);
1097                 if (el) {
1098                     if (!itemSvc.currently_generating) el.focus();
1099                     if (prev_bc && itemSvc.auto_gen_barcode && el.val() == "") {
1100                         itemSvc.nextBarcode(prev_bc).then(function(bc){
1101                             el.focus();
1102                             el.val(bc);
1103                             el.trigger('change');
1104                         });
1105                     } else {
1106                         itemSvc.currently_generating = false;
1107                     }
1108                 }
1109             }
1110         }
1111
1112         $scope.in_item_select = false;
1113         $scope.afterItemSelect = function() { $scope.in_item_select = false };
1114         $scope.handleItemSelect = function (item_list) {
1115             if (item_list && item_list.length > 0) {
1116                 $scope.in_item_select = true;
1117
1118                 angular.forEach(Object.keys($scope.defaults.attributes), function (attr) {
1119
1120                     var value_hash = {};
1121                     angular.forEach(item_list, function (item) {
1122                         if (item[attr]) {
1123                             var v = item[attr]()
1124                             if (angular.isObject(v)) {
1125                                 if (v.id) v = v.id();
1126                                 else if (v.code) v = v.code();
1127                             }
1128                             value_hash[v] = 1;
1129                         }
1130                     });
1131
1132                     if (Object.keys(value_hash).length == 1) {
1133                         if (attr == 'circ_lib') {
1134                             $scope.working[attr] = egCore.org.get(item_list[0][attr]());
1135                         } else {
1136                             $scope.working[attr] = item_list[0][attr]();
1137                         }
1138                     } else {
1139                         $scope.working[attr] = undefined;
1140                     }
1141                 });
1142
1143                 angular.forEach($scope.statcats, function (sc) {
1144
1145                     var counter = -1;
1146                     var value_hash = {};
1147                     var none = false;
1148                     angular.forEach(item_list, function (item) {
1149                         if (item.stat_cat_entries()) {
1150                             if (item.stat_cat_entries().length > 0) {
1151                                 var right_sc = item.stat_cat_entries().filter(function (e) {
1152                                     return e.stat_cat() == sc.id() && !Boolean(e.isdeleted());
1153                                 });
1154
1155                                 if (right_sc.length > 0) {
1156                                     value_hash[right_sc[0].stat_cat_entry()] = right_sc[0].stat_cat_entry();
1157                                 } else {
1158                                     none = true;
1159                                 }
1160                             }
1161                         } else {
1162                             none = true;
1163                         }
1164                     });
1165
1166                     if (!none && Object.keys(value_hash).length == 1) {
1167                         $scope.working.statcats[sc.id()] = value_hash[Object.keys(value_hash)[0]];
1168                     } else {
1169                         $scope.working.statcats[sc.id()] = undefined;
1170                     }
1171                 });
1172
1173             } else {
1174                 $scope.clearWorking();
1175             }
1176
1177         }
1178
1179         $scope.$watch('data.copies.length', function () {
1180             if ($scope.data.copies) {
1181                 var base_orgs = $scope.data.copies.map(function(cp){
1182                     return cp.circ_lib()
1183                 }).concat(
1184                     $scope.data.copies.map(function(cp){
1185                         return cp.call_number().owning_lib()
1186                     })
1187                 ).concat(
1188                     [egCore.auth.user().ws_ou()]
1189                 ).filter(function(e,i,a){
1190                     return a.lastIndexOf(e) === i;
1191                 });
1192
1193                 var all_orgs = [];
1194                 angular.forEach(base_orgs, function(o) {
1195                     all_orgs = all_orgs.concat( egCore.org.fullPath(o, true) );
1196                 });
1197
1198                 var final_orgs = all_orgs.filter(function(e,i,a){
1199                     return a.lastIndexOf(e) === i;
1200                 }).sort(function(a, b){return parseInt(a)-parseInt(b)});
1201
1202                 if ($scope.location_orgs.toString() != final_orgs.toString()) {
1203                     $scope.location_orgs = final_orgs;
1204                     if ($scope.location_orgs.length) {
1205                         itemSvc.get_locations($scope.location_orgs).then(function(list){
1206                             angular.forEach(list, function(l) {
1207                                 $scope.location_cache[ ''+l.id() ] = l;
1208                             });
1209                             $scope.location_list = list;
1210                         });
1211
1212                         $scope.statcat_filter_list = [];
1213                         angular.forEach($scope.location_orgs, function (o) {
1214                             $scope.statcat_filter_list.push(egCore.org.get(o));
1215                         });
1216
1217                         itemSvc.get_statcats($scope.location_orgs).then(function(list){
1218                             $scope.statcats = list;
1219                             angular.forEach($scope.statcats, function (s) {
1220
1221                                 if (!$scope.working)
1222                                     $scope.working = { statcats: {}, statcat_filter: undefined};
1223                                 if (!$scope.working.statcats)
1224                                     $scope.working.statcats = {};
1225
1226                                 if (!$scope.in_item_select) {
1227                                     $scope.working.statcats[s.id()] = undefined;
1228                                 }
1229                                 createStatcatUpdateWatcher(s.id());
1230                             });
1231                             $scope.in_item_select = false;
1232                         });
1233                     }
1234                 }
1235             }
1236
1237             $scope.workingGridDataProvider.refresh();
1238         });
1239
1240         $scope.suffix_list = [];
1241         itemSvc.get_suffixes(egCore.auth.user().ws_ou()).then(function(list){
1242             $scope.suffix_list = list;
1243         });
1244
1245         $scope.prefix_list = [];
1246         itemSvc.get_prefixes(egCore.auth.user().ws_ou()).then(function(list){
1247             $scope.prefix_list = list;
1248         });
1249
1250         $scope.classification_list = [];
1251         itemSvc.get_classifications().then(function(list){
1252             $scope.classification_list = list;
1253         });
1254
1255         $scope.$watch('completed_copies.length', function () {
1256             $scope.completedGridDataProvider.refresh();
1257         });
1258
1259         $scope.location_list = [];
1260         itemSvc.get_locations().then(function(list){
1261             $scope.location_list = list;
1262         });
1263         createSimpleUpdateWatcher('location');
1264
1265         $scope.status_list = [];
1266         itemSvc.get_statuses().then(function(list){
1267             $scope.status_list = list;
1268         });
1269         createSimpleUpdateWatcher('status');
1270
1271         $scope.circ_modifier_list = [];
1272         itemSvc.get_circ_mods().then(function(list){
1273             $scope.circ_modifier_list = list;
1274         });
1275         createSimpleUpdateWatcher('circ_modifier');
1276
1277         $scope.circ_type_list = [];
1278         itemSvc.get_circ_types().then(function(list){
1279             $scope.circ_type_list = list;
1280         });
1281         createSimpleUpdateWatcher('circ_as_type');
1282
1283         $scope.age_protect_list = [];
1284         itemSvc.get_age_protects().then(function(list){
1285             $scope.age_protect_list = list;
1286         });
1287         createSimpleUpdateWatcher('age_protect');
1288
1289         createSimpleUpdateWatcher('circ_lib');
1290         createSimpleUpdateWatcher('circulate');
1291         createSimpleUpdateWatcher('holdable');
1292         createSimpleUpdateWatcher('fine_level');
1293         createSimpleUpdateWatcher('loan_duration');
1294         createSimpleUpdateWatcher('cost');
1295         createSimpleUpdateWatcher('deposit');
1296         createSimpleUpdateWatcher('deposit_amount');
1297         createSimpleUpdateWatcher('mint_condition');
1298         createSimpleUpdateWatcher('opac_visible');
1299         createSimpleUpdateWatcher('ref');
1300
1301         $scope.saveCompletedCopies = function (and_exit) {
1302             var cnHash = {};
1303             var perCnCopies = {};
1304             angular.forEach( egCore.idl.Clone($scope.completed_copies), function (cp) {
1305                 var cn_id = cp.call_number().id();
1306                 if (!cnHash[cn_id]) {
1307                     cnHash[cn_id] = cp.call_number();
1308                     perCnCopies[cn_id] = [cp];
1309                 } else {
1310                     perCnCopies[cn_id].push(cp);
1311                 }
1312                 cp.call_number(cn_id); // prevent loops in JSON-ification
1313                 if (typeof cnHash[cn_id].prefix() == 'object')
1314                     cnHash[cn_id].prefix(cnHash[cn_id].prefix().id()); // un-object-ize some fields
1315                 if (typeof cnHash[cn_id].suffix() == 'object')
1316                     cnHash[cn_id].suffix(cnHash[cn_id].suffix().id()); // un-object-ize some fields
1317             });
1318
1319             angular.forEach(perCnCopies, function (v, k) {
1320                 cnHash[k].copies(v);
1321             });
1322
1323             cnList = [];
1324             angular.forEach(cnHash, function (v, k) {
1325                 cnList.push(v);
1326             });
1327
1328             egNet.request(
1329                 'open-ils.cat',
1330                 'open-ils.cat.asset.volume.fleshed.batch.update.override',
1331                 egCore.auth.token(), cnList, 1, { auto_merge_vols : 1, create_parts : 1 }
1332             ).then(function(update_count) {
1333                 if (and_exit) {
1334                     $scope.dirty = false;
1335                     $timeout(function(){$window.close()});
1336                 }
1337             });
1338         }
1339
1340         $scope.saveAndContinue = function () {
1341             $scope.saveCompletedCopies(false);
1342         }
1343
1344         $scope.workingSaveAndExit = function () {
1345             $scope.workingToComplete();
1346             $scope.saveAndExit();
1347         }
1348
1349         $scope.saveAndExit = function () {
1350             $scope.saveCompletedCopies(true);
1351         }
1352
1353     }
1354
1355     $scope.copy_notes_dialog = function(copy_list) {
1356         var default_pub = Boolean($scope.defaults.copy_notes_pub);
1357         if (!angular.isArray(copy_list)) copy_list = [copy_list];
1358
1359         return $modal.open({
1360             templateUrl: './cat/volcopy/t_copy_notes',
1361             animation: true,
1362             controller:
1363                    ['$scope','$modalInstance',
1364             function($scope , $modalInstance) {
1365                 $scope.focusNote = true;
1366                 $scope.note = {
1367                     creator : egCore.auth.user().id(),
1368                     title   : '',
1369                     value   : '',
1370                     pub     : default_pub,
1371                 };
1372
1373                 $scope.require_initials = false;
1374                 egCore.org.settings([
1375                     'ui.staff.require_initials.copy_notes'
1376                 ]).then(function(set) {
1377                     $scope.require_initials = Boolean(set['ui.staff.require_initials.copy_notes']);
1378                 });
1379
1380                 $scope.note_list = [];
1381                 if (copy_list.length == 1) {
1382                     $scope.note_list = copy_list[0].notes();
1383                 }
1384
1385                 $scope.ok = function(note) {
1386
1387                     if (note.initials) note.value += ' [' + note.initials + ']';
1388                     angular.forEach(copy_list, function (cp) {
1389                         var n = new egCore.idl.acpn();
1390                         n.creator(note.creator);
1391                         n.pub(note.pub);
1392                         n.title(note.title);
1393                         n.value(note.value);
1394                         n.owning_copy(cp.id());
1395                         cp.notes().push( n );
1396                     });
1397
1398                     $modalInstance.close();
1399                 }
1400
1401                 $scope.cancel = function($event) {
1402                     $modalInstance.dismiss();
1403                     $event.preventDefault();
1404                 }
1405             }]
1406         });
1407     }
1408
1409 }])
1410
1411 .directive("egVolTemplate", function () {
1412     return {
1413         restrict: 'E',
1414         replace: true,
1415         template: '<div ng-include="'+"'/eg/staff/cat/volcopy/t_attr_edit'"+'"></div>',
1416         scope: { },
1417         controller : ['$scope','$window','itemSvc','egCore',
1418             function ( $scope , $window , itemSvc , egCore ) {
1419
1420                 $scope.defaults = { // If defaults are not set at all, allow everything
1421                     barcode_checkdigit : false,
1422                     auto_gen_barcode : false,
1423                     statcats : true,
1424                     copy_notes : true,
1425                     attributes : {
1426                         status : true,
1427                         loan_duration : true,
1428                         fine_level : true,
1429                         cost : true,
1430                         alerts : true,
1431                         deposit : true,
1432                         deposit_amount : true,
1433                         opac_visible : true,
1434                         price : true,
1435                         circulate : true,
1436                         mint_condition : true,
1437                         circ_lib : true,
1438                         ref : true,
1439                         circ_modifier : true,
1440                         circ_as_type : true,
1441                         location : true,
1442                         holdable : true,
1443                         age_protect : true
1444                     }
1445                 };
1446
1447                 $scope.fetchDefaults = function () {
1448                     egCore.hatch.getItem('cat.copy.defaults').then(function(t) {
1449                         if (t) {
1450                             $scope.defaults = t;
1451                             $scope.working.statcat_filter = $scope.defaults.statcat_filter;
1452                         }
1453                     });
1454                 }
1455                 $scope.fetchDefaults();
1456
1457                 $scope.dirty = false;
1458                 $scope.$watch('dirty',
1459                     function(newVal, oldVal) {
1460                         if (newVal && newVal != oldVal) {
1461                             $($window).on('beforeunload.template', function(){
1462                                 return 'There is unsaved template data!'
1463                             });
1464                         } else {
1465                             $($window).off('beforeunload.template');
1466                         }
1467                     }
1468                 );
1469
1470                 $scope.template_controls = true;
1471
1472                 $scope.fetchTemplates = function () {
1473                     egCore.hatch.getItem('cat.copy.templates').then(function(t) {
1474                         if (t) {
1475                             $scope.templates = t;
1476                             $scope.template_name_list = Object.keys(t);
1477                         }
1478                     });
1479                 }
1480                 $scope.fetchTemplates();
1481             
1482                 $scope.applyTemplate = function (n) {
1483                     angular.forEach($scope.templates[n], function (v,k) {
1484                         if (k == 'circ_lib') {
1485                             $scope.working[k] = egCore.org.get(v);
1486                         } else if (!angular.isObject(v)) {
1487                             $scope.working[k] = angular.copy(v);
1488                         } else {
1489                             angular.forEach(v, function (sv,sk) {
1490                                 $scope.working[k][sk] = angular.copy(sv);
1491                             });
1492                         }
1493                     });
1494                     $scope.template_name = '';
1495                 }
1496
1497                 $scope.deleteTemplate = function (n) {
1498                     if (n) {
1499                         delete $scope.templates[n]
1500                         $scope.template_name_list = Object.keys($scope.templates);
1501                         $scope.template_name = '';
1502                         egCore.hatch.setItem('cat.copy.templates', $scope.templates);
1503                         $scope.$parent.fetchTemplates();
1504                     }
1505                 }
1506
1507                 $scope.saveTemplate = function (n) {
1508                     if (n) {
1509                         var tmpl = {};
1510             
1511                         angular.forEach($scope.working, function (v,k) {
1512                             if (angular.isObject(v)) { // we'll use the pkey
1513                                 if (v.id) v = v.id();
1514                                 else if (v.code) v = v.code();
1515                             }
1516             
1517                             tmpl[k] = v;
1518                         });
1519             
1520                         $scope.templates[n] = tmpl;
1521                         $scope.template_name_list = Object.keys($scope.templates);
1522             
1523                         egCore.hatch.setItem('cat.copy.templates', $scope.templates);
1524                         $scope.$parent.fetchTemplates();
1525
1526                         $scope.dirty = false;
1527                     }
1528                 }
1529             
1530                 $scope.templates = {};
1531                 $scope.template_name = '';
1532                 $scope.template_name_list = [];
1533             
1534                 $scope.tracker = function (x,f) { if (x) return x[f]() };
1535                 $scope.idTracker = function (x) { if (x) return $scope.tracker(x,'id') };
1536                 $scope.cant_have_vols = function (id) { return !egCore.org.CanHaveVolumes(id); };
1537             
1538                 $scope.orgById = function (id) { return egCore.org.get(id) }
1539                 $scope.statusById = function (id) {
1540                     return $scope.status_list.filter( function (s) { return s.id() == id } )[0];
1541                 }
1542                 $scope.locationById = function (id) {
1543                     return $scope.location_cache[''+id];
1544                 }
1545             
1546                 createSimpleUpdateWatcher = function (field) {
1547                     $scope.$watch('working.' + field, function () {
1548                         var newval = $scope.working[field];
1549             
1550                         if (typeof newval != 'undefined') {
1551                             $scope.dirty = true;
1552                             if (angular.isObject(newval)) { // we'll use the pkey
1553                                 if (newval.id) $scope.working[field] = newval.id();
1554                                 else if (newval.code) $scope.working[field] = newval.code();
1555                             }
1556             
1557                             if (""+newval == "" || newval == null) {
1558                                 $scope.working[field] = undefined;
1559                             }
1560             
1561                         }
1562                     });
1563                 }
1564             
1565                 $scope.working = {
1566                     statcats: {},
1567                     statcat_filter: undefined
1568                 };
1569             
1570                 createStatcatUpdateWatcher = function (id) {
1571                     return $scope.$watch('working.statcats[' + id + ']', function () {
1572                         if ($scope.working.statcats) {
1573                             var newval = $scope.working.statcats[id];
1574                 
1575                             if (typeof newval != 'undefined') {
1576                                 $scope.dirty = true;
1577                                 if (angular.isObject(newval)) { // we'll use the pkey
1578                                     newval = newval.id();
1579                                 }
1580                 
1581                                 if (""+newval == "" || newval == null) {
1582                                     $scope.working.statcats[id] = undefined;
1583                                     newval = null;
1584                                 }
1585                 
1586                             }
1587                         }
1588                     });
1589                 }
1590
1591                 $scope.clearWorking = function () {
1592                     angular.forEach($scope.working, function (v,k,o) {
1593                         if (!angular.isObject(v)) {
1594                             if (typeof v != 'undefined')
1595                                 $scope.working[k] = undefined;
1596                         } else if (k != 'circ_lib') {
1597                             angular.forEach(v, function (sv,sk) {
1598                                 $scope.working[k][sk] = undefined;
1599                             });
1600                         }
1601                     });
1602                     $scope.working.circ_lib = undefined; // special
1603                     $scope.dirty = false;
1604                 }
1605
1606                 $scope.working = {};
1607                 $scope.location_orgs = [];
1608                 $scope.location_cache = {};
1609             
1610                 $scope.location_list = [];
1611                 itemSvc.get_locations(
1612                     egCore.org.fullPath( egCore.auth.user().ws_ou(), true )
1613                 ).then(function(list){
1614                     $scope.location_list = list;
1615                 });
1616                 createSimpleUpdateWatcher('location');
1617
1618                 $scope.statcat_filter_list = egCore.org.fullPath( egCore.auth.user().ws_ou() );
1619
1620                 $scope.statcats = [];
1621                 itemSvc.get_statcats(
1622                     egCore.org.fullPath( egCore.auth.user().ws_ou(), true )
1623                 ).then(function(list){
1624                     $scope.statcats = list;
1625                     angular.forEach($scope.statcats, function (s) {
1626
1627                         if (!$scope.working)
1628                             $scope.working = { statcats: {}, statcat_filter: undefined};
1629                         if (!$scope.working.statcats)
1630                             $scope.working.statcats = {};
1631
1632                         $scope.working.statcats[s.id()] = undefined;
1633                         createStatcatUpdateWatcher(s.id());
1634                     });
1635                 });
1636             
1637                 $scope.status_list = [];
1638                 itemSvc.get_statuses().then(function(list){
1639                     $scope.status_list = list;
1640                 });
1641                 createSimpleUpdateWatcher('status');
1642             
1643                 $scope.circ_modifier_list = [];
1644                 itemSvc.get_circ_mods().then(function(list){
1645                     $scope.circ_modifier_list = list;
1646                 });
1647                 createSimpleUpdateWatcher('circ_modifier');
1648             
1649                 $scope.circ_type_list = [];
1650                 itemSvc.get_circ_types().then(function(list){
1651                     $scope.circ_type_list = list;
1652                 });
1653                 createSimpleUpdateWatcher('circ_as_type');
1654             
1655                 $scope.age_protect_list = [];
1656                 itemSvc.get_age_protects().then(function(list){
1657                     $scope.age_protect_list = list;
1658                 });
1659                 createSimpleUpdateWatcher('age_protect');
1660             
1661                 createSimpleUpdateWatcher('circulate');
1662                 createSimpleUpdateWatcher('holdable');
1663                 createSimpleUpdateWatcher('fine_level');
1664                 createSimpleUpdateWatcher('loan_duration');
1665                 createSimpleUpdateWatcher('cost');
1666                 createSimpleUpdateWatcher('deposit');
1667                 createSimpleUpdateWatcher('deposit_amount');
1668                 createSimpleUpdateWatcher('mint_condition');
1669                 createSimpleUpdateWatcher('opac_visible');
1670                 createSimpleUpdateWatcher('ref');
1671
1672                 $scope.suffix_list = [];
1673                 itemSvc.get_suffixes(egCore.auth.user().ws_ou()).then(function(list){
1674                     $scope.suffix_list = list;
1675                 });
1676
1677                 $scope.prefix_list = [];
1678                 itemSvc.get_prefixes(egCore.auth.user().ws_ou()).then(function(list){
1679                     $scope.prefix_list = list;
1680                 });
1681
1682                 $scope.classification_list = [];
1683                 itemSvc.get_classifications().then(function(list){
1684                     $scope.classification_list = list;
1685                 });
1686
1687                 createSimpleUpdateWatcher('working.callnumber.classification');
1688                 createSimpleUpdateWatcher('working.callnumber.prefix');
1689                 createSimpleUpdateWatcher('working.callnumber.suffix');
1690             }
1691         ]
1692     }
1693 })
1694
1695