]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/cat/volcopy/app.js
46842460f4eeb0211e05a58a381e2a56ba73bf56
[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 eg-disabled="record == 0" list="parts" selected="part"></eg-basic-combo-box></div>'+
256             '</div>',
257
258         scope: { focusNext: "=", copy: "=", callNumber: "=", index: "@", record: "@" },
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 ng-disabled="record == 0" 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 ng-disabled="record == 0" 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 ng-disabled="record == 0" class="form-control" type="text" ng-change="updateLabel()" ng-model="label"/></div>'+
337                 '<div class="col-xs-1">'+
338                     '<select ng-disabled="record == 0" 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 ng-disabled="record == 0" 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 record="{{record}}" 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: "=", record: "@" },
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.callNumber.owning_lib() );
467                         cp.call_number( $scope.callNumber );
468                         cp.deposit(0);
469                         cp.price(0);
470                         cp.deposit_amount(0);
471                         cp.fine_level(2); // Normal
472                         cp.loan_duration(2); // Normal
473                         cp.location(1); // Stacks
474                         cp.circulate('t');
475                         cp.holdable('t');
476                         cp.opac_visible('t');
477                         cp.ref('f');
478                         cp.mint_condition('t');
479                         $scope.copies.push( cp );
480                         $scope.allcopies.push( cp );
481
482                     }
483
484                     if ($scope.copy_count >= $scope.orig_copy_count) {
485                         var how_many = $scope.copies.length - $scope.copy_count;
486                         if (how_many > 0) {
487                             var dead = $scope.copies.splice($scope.copy_count,how_many);
488                             $scope.callNumber.copies($scope.copies);
489
490                             // Trimming the global list is a bit more tricky
491                             angular.forEach( dead, function (d) {
492                                 angular.forEach( $scope.allcopies, function (l, i) { 
493                                     if (l === d) $scope.allcopies.splice(i,1);
494                                 });
495                             });
496                         }
497                     }
498                 }
499
500             }
501         ]
502
503     }
504 })
505
506 .directive("egVolEdit", function () {
507     return {
508         restrict: 'E',
509         replace: true,
510         template:
511             '<div class="row">'+
512                 '<div class="col-xs-1"><eg-org-selector alldisabled="{{record == 0}}" selected="owning_lib" disable-test="cant_have_vols"></eg-org-selector></div>'+
513                 '<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>'+
514                 '<div class="col-xs-10">'+
515                     '<eg-vol-row only-vols="onlyVols" record="{{record}}"'+
516                         'ng-repeat="(cn,copies) in struct | orderBy:cn track by cn" '+
517                         'focus-next="focusNextFirst" copies="copies" allcopies="allcopies">'+
518                     '</eg-vol-row>'+
519                 '</div>'+
520             '</div>',
521
522         scope: { focusNext: "=", allcopies: "=", struct: "=", lib: "@", record: "@", onlyVols: "=" },
523         controller : ['$scope','itemSvc','egCore',
524             function ( $scope , itemSvc , egCore ) {
525                 $scope.first_cn = Object.keys($scope.struct)[0];
526                 $scope.full_cn = $scope.struct[$scope.first_cn][0].call_number();
527
528                 $scope.defaults = {};
529                 egCore.hatch.getItem('cat.copy.defaults').then(function(t) {
530                     if (t) {
531                         $scope.defaults = t;
532                     }
533                 });
534
535                 $scope.focusNextFirst = function(prev_cn,prev_bc) {
536                     var n;
537                     var yep = false;
538                     angular.forEach(Object.keys($scope.struct).sort(), function (cn) {
539                         if (n) return;
540
541                         if (cn == prev_cn) {
542                             yep = true;
543                             return;
544                         }
545
546                         if (yep) n = cn;
547                     });
548
549                     if (n) {
550                         var next = '#' + n + '_' + $scope.struct[n][0].id();
551                         var el = $(next);
552                         if (el) {
553                             if (!itemSvc.currently_generating) el.focus();
554                             if (prev_bc && itemSvc.auto_gen_barcode && el.val() == "") {
555                                 itemSvc.nextBarcode(prev_bc).then(function(bc){
556                                     el.focus();
557                                     el.val(bc);
558                                     el.trigger('change');
559                                 });
560                             } else {
561                                 itemSvc.currently_generating = false;
562                             }
563                         }
564                     } else {
565                         $scope.focusNext($scope.lib, prev_bc);
566                     }
567                 }
568
569                 $scope.cn_count = Object.keys($scope.struct).length;
570                 $scope.orig_cn_count = $scope.cn_count;
571
572                 $scope.owning_lib = egCore.org.get($scope.lib);
573                 $scope.$watch('owning_lib', function (l) {
574                     angular.forEach( $scope.struct[$scope.first_cn], function (cp) {
575                         cp.call_number().owning_lib( $scope.owning_lib.id() );
576                     });
577                 });
578
579                 $scope.cant_have_vols = function (id) { return !egCore.org.CanHaveVolumes(id); };
580
581                 $scope.$watch('cn_count', function (n) {
582                     var o = Object.keys($scope.struct).length;
583                     if (n > o) { // adding
584                         for (var i = o; o < n; o++) {
585                             var cn = new egCore.idl.acn();
586                             cn.id( --itemSvc.new_cn_id );
587                             cn.isnew( true );
588                             cn.prefix( $scope.defaults.prefix || -1 );
589                             cn.suffix( $scope.defaults.suffix || -1 );
590                             cn.label_class( $scope.defaults.classification || 1 );
591                             cn.owning_lib( $scope.owning_lib.id() );
592                             cn.record( $scope.full_cn.record() );
593
594                             var cp = new egCore.idl.acp();
595                             cp.call_number( cn );
596                             cp.id( --itemSvc.new_cp_id );
597                             cp.isnew( true );
598
599                             cp.deposit(0);
600                             cp.price(0);
601                             cp.deposit_amount(0);
602                             cp.fine_level(2); // Normal
603                             cp.loan_duration(2); // Normal
604                             cp.location(1); // Stacks
605                             cp.circulate('t');
606                             cp.holdable('t');
607                             cp.opac_visible('t');
608                             cp.ref('f');
609                             cp.mint_condition('t');
610
611                             cp.circ_lib( $scope.owning_lib.id() );
612                             cp.call_number( cn );
613
614                             $scope.struct[cn.id()] = [cp];
615                             $scope.allcopies.push(cp);
616                         }
617                     } else if (n < o && n >= $scope.orig_cn_count) { // removing
618                         var how_many = o - n;
619                         var list = Object
620                                 .keys($scope.struct)
621                                 .sort(function(a, b){return parseInt(a)-parseInt(b)})
622                                 .filter(function(x){ return parseInt(x) <= 0 });
623                         for (var i = 0; i < how_many; i++) {
624                             // Trimming the global list is a bit more tricky
625                             angular.forEach($scope.struct[list[i]], function (d) {
626                                 angular.forEach( $scope.allcopies, function (l, j) { 
627                                     if (l === d) $scope.allcopies.splice(j,1);
628                                 });
629                             });
630                             delete $scope.struct[list[i]];
631                         }
632                     }
633                 });
634             }
635         ]
636
637     }
638 })
639
640 /**
641  * Edit controller!
642  */
643 .controller('EditCtrl', 
644        ['$scope','$q','$window','$routeParams','$location','$timeout','egCore','egNet','egGridDataProvider','itemSvc','$modal',
645 function($scope , $q , $window , $routeParams , $location , $timeout , egCore , egNet , egGridDataProvider , itemSvc , $modal) {
646
647     $scope.defaults = { // If defaults are not set at all, allow everything
648         barcode_checkdigit : false,
649         auto_gen_barcode : false,
650         statcats : true,
651         copy_notes : true,
652         attributes : {
653             status : true,
654             loan_duration : true,
655             fine_level : true,
656             cost : true,
657             alerts : true,
658             deposit : true,
659             deposit_amount : true,
660             opac_visible : true,
661             price : true,
662             circulate : true,
663             mint_condition : true,
664             circ_lib : true,
665             ref : true,
666             circ_modifier : true,
667             circ_as_type : true,
668             location : true,
669             holdable : true,
670             age_protect : true
671         }
672     };
673
674     $scope.embedded = ($routeParams.mode && $routeParams.mode == 'embedded') ? true : false;
675
676     $scope.saveDefaults = function () {
677         egCore.hatch.setItem('cat.copy.defaults', $scope.defaults);
678     }
679
680     $scope.fetchDefaults = function () {
681         egCore.hatch.getItem('cat.copy.defaults').then(function(t) {
682             if (t) {
683                 $scope.defaults = t;
684                 if (!$scope.batch) $scope.batch = {};
685                 $scope.batch.classification = $scope.defaults.classification;
686                 $scope.batch.prefix = $scope.defaults.prefix;
687                 $scope.batch.suffix = $scope.defaults.suffix;
688                 $scope.working.statcat_filter = $scope.defaults.statcat_filter;
689                 if ($scope.defaults.always_volumes) $scope.show_vols = true;
690                 if ($scope.defaults.barcode_checkdigit) itemSvc.barcode_checkdigit = true;
691                 if ($scope.defaults.auto_gen_barcode) itemSvc.auto_gen_barcode = true;
692             }
693         });
694     }
695     $scope.fetchDefaults();
696
697     $scope.$watch('defaults.auto_gen_barcode', function (n,o) {
698         itemSvc.auto_gen_barcode = n
699     });
700
701     $scope.$watch('defaults.barcode_checkdigit', function (n,o) {
702         itemSvc.barcode_checkdigit = n
703     });
704
705     $scope.dirty = false;
706     $scope.$watch('dirty',
707         function(newVal, oldVal) {
708             if (newVal && newVal != oldVal) {
709                 $($window).on('beforeunload.edit', function(){
710                     return 'There is unsaved data!'
711                 });
712             } else {
713                 $($window).off('beforeunload.edit');
714             }
715         }
716     );
717
718     $scope.only_vols = false;
719     $scope.show_vols = true;
720     $scope.show_copies = true;
721
722     $scope.tracker = function (x,f) { if (x) return x[f]() };
723     $scope.idTracker = function (x) { if (x) return $scope.tracker(x,'id') };
724     $scope.cant_have_vols = function (id) { return !egCore.org.CanHaveVolumes(id); };
725
726     $scope.orgById = function (id) { return egCore.org.get(id) }
727     $scope.statusById = function (id) {
728         return $scope.status_list.filter( function (s) { return s.id() == id } )[0];
729     }
730     $scope.locationById = function (id) {
731         return $scope.location_cache[''+id];
732     }
733
734     $scope.workingToComplete = function () {
735         angular.forEach( $scope.workingGridControls.selectedItems(), function (c) {
736             angular.forEach( itemSvc.copies, function (w, i) {
737                 if (c === w)
738                     $scope.completed_copies = $scope.completed_copies.concat(itemSvc.copies.splice(i,1));
739             });
740         });
741
742         return true;
743     }
744
745     $scope.completeToWorking = function () {
746         angular.forEach( $scope.completedGridControls.selectedItems(), function (c) {
747             angular.forEach( $scope.completed_copies, function (w, i) {
748                 if (c === w)
749                     itemSvc.copies = itemSvc.copies.concat($scope.completed_copies.splice(i,1));
750             });
751         });
752
753         return true;
754     }
755
756     createSimpleUpdateWatcher = function (field) {
757         return $scope.$watch('working.' + field, function () {
758             var newval = $scope.working[field];
759
760             if (typeof newval != 'undefined') {
761                 if (angular.isObject(newval)) { // we'll use the pkey
762                     if (newval.id) newval = newval.id();
763                     else if (newval.code) newval = newval.code();
764                 }
765
766                 if (""+newval == "" || newval == null) {
767                     $scope.working[field] = undefined;
768                     newval = null;
769                 }
770
771                 if ($scope.workingGridControls && $scope.workingGridControls.selectedItems) {
772                     angular.forEach(
773                         $scope.workingGridControls.selectedItems(),
774                         function (cp) {
775                             if (cp[field]() !== newval) {
776                                 cp[field](newval);
777                                 cp.ischanged(1);
778                                 $scope.dirty = true;
779                             }
780                         }
781                     );
782                 }
783             }
784         });
785     }
786
787     $scope.working = {
788         statcats: {},
789         statcat_filter: undefined
790     };
791
792     $scope.statcatUpdate = function (id) {
793         var newval = $scope.working.statcats[id];
794
795         if (typeof newval != 'undefined') {
796             if (angular.isObject(newval)) { // we'll use the pkey
797                 newval = newval.id();
798             }
799     
800             if (""+newval == "" || newval == null) {
801                 $scope.working.statcats[id] = undefined;
802                 newval = null;
803             }
804     
805             if (!$scope.in_item_select && $scope.workingGridControls && $scope.workingGridControls.selectedItems) {
806                 angular.forEach(
807                     $scope.workingGridControls.selectedItems(),
808                     function (cp) {
809                         $scope.dirty = true;
810
811                         cp.stat_cat_entries(
812                             angular.forEach( cp.stat_cat_entries(), function (e) {
813                                 if (e.stat_cat() == id) { // mark deleted
814                                     e.isdeleted(1);
815                                 }
816                             })
817                         );
818     
819                         if (newval) {
820                             var e = new egCore.idl.ascecm();
821                             e.isnew( 1 );
822                             e.owning_copy( cp.id() );
823                             e.stat_cat( id );
824                             e.stat_cat_entry( newval );
825
826                             cp.stat_cat_entries(
827                                 cp.stat_cat_entries().concat([ e ])
828                             );
829
830                         }
831
832                         cp.stat_cat_entries( // trim out ephemeral deleted ones
833                             cp.stat_cat_entries().filter(function (e) {
834                                 if (Boolean(e.isnew())) {
835                                     if (Boolean(e.isdeleted())) {
836                                         return false;
837                                     }
838                                 }
839                                 return true;
840                             })
841                         );
842    
843                         cp.ischanged(1);
844                     }
845                 );
846             }
847         }
848     }
849
850     var dataKey = $routeParams.dataKey;
851     console.debug('dataKey: ' + dataKey);
852
853     if (dataKey && dataKey.length > 0) {
854
855         $scope.templates = {};
856         $scope.template_name = '';
857         $scope.template_name_list = [];
858
859         $scope.fetchTemplates = function () {
860             egCore.hatch.getItem('cat.copy.templates').then(function(t) {
861                 if (t) {
862                     $scope.templates = t;
863                     $scope.template_name_list = Object.keys(t);
864                 }
865             });
866             egCore.hatch.getItem('cat.copy.last_template').then(function(t) {
867                 if (t) $scope.template_name = t;
868             });
869         }
870         $scope.fetchTemplates();
871
872         $scope.applyTemplate = function (n) {
873             angular.forEach($scope.templates[n], function (v,k) {
874                 if (k == 'circ_lib') {
875                     $scope.working[k] = egCore.org.get(v);
876                 } else if (!angular.isObject(v)) {
877                     $scope.working[k] = angular.copy(v);
878                 } else {
879                     angular.forEach(v, function (sv,sk) {
880                         if (k == 'callnumber') {
881                             angular.forEach(v, function (cnv,cnk) {
882                                 $scope.batch[cnk] = cnv;
883                             });
884                             $scope.applyBatchCNValues();
885                         } else {
886                             $scope.working[k][sk] = angular.copy(sv);
887                             if (k == 'statcats') $scope.statcatUpdate(sk);
888                         }
889                     });
890                 }
891             });
892             egCore.hatch.setItem('cat.copy.last_template', n);
893         }
894
895         $scope.copytab = 'working';
896         $scope.tab = 'edit';
897         $scope.summaryRecord = null;
898         $scope.record_id = null;
899         $scope.data = {};
900         $scope.completed_copies = [];
901         $scope.location_orgs = [];
902         $scope.location_cache = {};
903         $scope.statcats = [];
904         if (!$scope.batch) $scope.batch = {};
905
906         $scope.applyBatchCNValues = function () {
907             if ($scope.data.tree) {
908                 angular.forEach($scope.data.tree, function(cn_hash) {
909                     angular.forEach(cn_hash, function(copies) {
910                         angular.forEach(copies, function(cp) {
911                             if (typeof $scope.batch.classification != 'undefined' && $scope.batch.classification != '') {
912                                 var label_class = $scope.classification_list.filter(function(p){ return p.id() == $scope.batch.classification })[0];
913                                 cp.call_number().label_class(label_class);
914                                 cp.call_number().ischanged(1);
915                                 $scope.dirty = true;
916                             }
917                             if (typeof $scope.batch.prefix != 'undefined' && $scope.batch.prefix != '') {
918                                 var prefix = $scope.prefix_list.filter(function(p){ return p.id() == $scope.batch.prefix })[0];
919                                 cp.call_number().prefix(prefix);
920                                 cp.call_number().ischanged(1);
921                                 $scope.dirty = true;
922                             }
923                             if (typeof $scope.batch.label != 'undefined' && $scope.batch.label != '') {
924                                 cp.call_number().label($scope.batch.label);
925                                 cp.call_number().ischanged(1);
926                                 $scope.dirty = true;
927                             }
928                             if (typeof $scope.batch.suffix != 'undefined' && $scope.batch.suffix != '') {
929                                 var suffix = $scope.suffix_list.filter(function(p){ return p.id() == $scope.batch.suffix })[0];
930                                 cp.call_number().suffix(suffix);
931                                 cp.call_number().ischanged(1);
932                                 $scope.dirty = true;
933                             }
934                         });
935                     });
936                 });
937             }
938         }
939
940         $scope.clearWorking = function () {
941             angular.forEach($scope.working, function (v,k,o) {
942                 if (!angular.isObject(v)) {
943                     if (typeof v != 'undefined')
944                         $scope.working[k] = undefined;
945                 } else if (k != 'circ_lib') {
946                     angular.forEach(v, function (sv,sk) {
947                         if (typeof v != 'undefined')
948                             $scope.working[k][sk] = undefined;
949                     });
950                 }
951             });
952             $scope.working.circ_lib = undefined; // special
953         }
954
955         $scope.completedGridDataProvider = egGridDataProvider.instance({
956             get : function(offset, count) {
957                 //return provider.arrayNotifier(itemSvc.copies, offset, count);
958                 return this.arrayNotifier($scope.completed_copies, offset, count);
959             }
960         });
961
962         $scope.completedGridControls = {};
963
964         $scope.workingGridDataProvider = egGridDataProvider.instance({
965             get : function(offset, count) {
966                 //return provider.arrayNotifier(itemSvc.copies, offset, count);
967                 return this.arrayNotifier(itemSvc.copies, offset, count);
968             }
969         });
970
971         $scope.workingGridControls = {};
972         $scope.add_vols_copies = false;
973         $scope.is_fast_add = false;
974
975         egNet.request(
976             'open-ils.actor',
977             'open-ils.actor.anon_cache.get_value',
978             dataKey, 'edit-these-copies'
979         ).then(function (data) {
980
981             if (data) {
982                 if (data.hide_vols && !$scope.defaults.always_volumes) $scope.show_vols = false;
983                 if (data.hide_copies) {
984                     $scope.show_copies = false;
985                     $scope.only_vols = true;
986                 }
987
988                 $scope.record_id = data.record_id;
989
990                 function fetchRaw () {
991                     if (!$scope.only_vols) $scope.dirty = true;
992                     $scope.add_vols_copies = true;
993
994                     /* data.raw data structure looks like this:
995                      * [{
996                      *      callnumber : $cn_id, // optional, to add a copy to a cn
997                      *      owner      : $org, // optional, defaults to ws_ou
998                      *      label      : $cn_label, // optional, to supply a label on a new cn
999                      *      barcode    : $cp_barcode // optional, to supply a barcode on a new cp
1000                      *      fast_add   : boolean // optional, to specify whether this came
1001                      *                              in as a fast add
1002                      * },...]
1003                      * 
1004                      * All can be left out and a completely empty vol/copy combo will be vivicated.
1005                      */
1006
1007                     angular.forEach(
1008                         data.raw,
1009                         function (proto) {
1010                             if (proto.fast_add) $scope.is_fast_add = true;
1011                             if (proto.callnumber) {
1012                                 return egCore.pcrud.retrieve('acn', proto.callnumber)
1013                                 .then(function(cn) {
1014                                     var cp = new egCore.idl.acp();
1015                                     cp.call_number( cn );
1016                                     cp.id( --itemSvc.new_cp_id );
1017                                     if (!$scope.only_vols) cp.isnew( true );
1018                                     cp.circ_lib( proto.owner || egCore.auth.user().ws_ou() );
1019
1020                                     cp.deposit(0);
1021                                     cp.price(0);
1022                                     cp.deposit_amount(0);
1023                                     cp.fine_level(2); // Normal
1024                                     cp.loan_duration(2); // Normal
1025                                     cp.location(1); // Stacks
1026                                     cp.circulate('t');
1027                                     cp.holdable('t');
1028                                     cp.opac_visible('t');
1029                                     cp.ref('f');
1030                                     cp.mint_condition('t');
1031
1032                                     if (proto.barcode) cp.barcode( proto.barcode );
1033
1034                                     itemSvc.addCopy(cp)
1035                                 });
1036                             } else {
1037                                 var cn = new egCore.idl.acn();
1038                                 cn.id( --itemSvc.new_cn_id );
1039                                 cn.isnew( true );
1040                                 cn.prefix( $scope.defaults.prefix || -1 );
1041                                 cn.suffix( $scope.defaults.suffix || -1 );
1042                                 cn.label_class( $scope.defaults.classification || 1 );
1043                                 cn.owning_lib( proto.owner || egCore.auth.user().ws_ou() );
1044                                 cn.record( $scope.record_id );
1045                                 if (proto.label) cn.label( proto.label );
1046
1047                                 var cp = new egCore.idl.acp();
1048                                 cp.call_number( cn );
1049                                 cp.id( --itemSvc.new_cp_id );
1050                                 cp.isnew( true );
1051
1052                                 cp.deposit(0);
1053                                 cp.price(0);
1054                                 cp.deposit_amount(0);
1055                                 cp.fine_level(2); // Normal
1056                                 cp.loan_duration(2); // Normal
1057                                 cp.location(1); // Stacks
1058                                 cp.circulate('t');
1059                                 cp.holdable('t');
1060                                 cp.opac_visible('t');
1061                                 cp.ref('f');
1062                                 cp.mint_condition('t');
1063
1064                                 cp.circ_lib( proto.owner || egCore.auth.user().ws_ou() );
1065                                 if (proto.barcode) cp.barcode( proto.barcode );
1066
1067                                 itemSvc.addCopy(cp)
1068                             }
1069     
1070                         }
1071                     );
1072
1073                     return itemSvc.copies;
1074                 }
1075
1076                 if (data.copies && data.copies.length)
1077                     return itemSvc.fetchIds(data.copies).then(fetchRaw);
1078
1079                 return fetchRaw();
1080
1081             }
1082
1083         }).then( function() {
1084             $scope.data = itemSvc;
1085             if ($scope.add_vols_copies) {
1086                 var status_setting = $scope.is_fast_add ?
1087                     'cat.default_copy_status_fast' :
1088                     'cat.default_copy_status_normal';
1089                 egCore.org.settings([
1090                     status_setting
1091                 ]).then(function(set) {
1092                     $scope.default_ccs = set[status_setting] || 
1093                         ($scope.is_fast_add ? 0 : 5); // 0 is Available, 5 is In Process
1094                     angular.forEach($scope.data.copies, function (cp) {
1095                         cp.status($scope.default_ccs);
1096                     });
1097                     $scope.workingGridDataProvider.refresh();
1098                 });
1099             }
1100         });
1101
1102         $scope.focusNextFirst = function(prev_lib,prev_bc) {
1103             var n;
1104             var yep = false;
1105             angular.forEach(Object.keys($scope.data.tree).sort(), function (lib) {
1106                 if (n) return;
1107
1108                 if (lib == prev_lib) {
1109                     yep = true;
1110                     return;
1111                 }
1112
1113                 if (yep) n = lib;
1114             });
1115
1116             if (n) {
1117                 var first_cn = Object.keys($scope.data.tree[n])[0];
1118                 var next = '#' + first_cn + '_' + $scope.data.tree[n][first_cn][0].id();
1119                 var el = $(next);
1120                 if (el) {
1121                     if (!itemSvc.currently_generating) el.focus();
1122                     if (prev_bc && itemSvc.auto_gen_barcode && el.val() == "") {
1123                         itemSvc.nextBarcode(prev_bc).then(function(bc){
1124                             el.focus();
1125                             el.val(bc);
1126                             el.trigger('change');
1127                         });
1128                     } else {
1129                         itemSvc.currently_generating = false;
1130                     }
1131                 }
1132             }
1133         }
1134
1135         $scope.in_item_select = false;
1136         $scope.afterItemSelect = function() { $scope.in_item_select = false };
1137         $scope.handleItemSelect = function (item_list) {
1138             if (item_list && item_list.length > 0) {
1139                 $scope.in_item_select = true;
1140
1141                 angular.forEach(Object.keys($scope.defaults.attributes), function (attr) {
1142
1143                     var value_hash = {};
1144                     angular.forEach(item_list, function (item) {
1145                         if (item[attr]) {
1146                             var v = item[attr]()
1147                             if (angular.isObject(v)) {
1148                                 if (v.id) v = v.id();
1149                                 else if (v.code) v = v.code();
1150                             }
1151                             value_hash[v] = 1;
1152                         }
1153                     });
1154
1155                     if (Object.keys(value_hash).length == 1) {
1156                         if (attr == 'circ_lib') {
1157                             $scope.working[attr] = egCore.org.get(item_list[0][attr]());
1158                         } else {
1159                             $scope.working[attr] = item_list[0][attr]();
1160                         }
1161                     } else {
1162                         $scope.working[attr] = undefined;
1163                     }
1164                 });
1165
1166                 angular.forEach($scope.statcats, function (sc) {
1167
1168                     var counter = -1;
1169                     var value_hash = {};
1170                     var none = false;
1171                     angular.forEach(item_list, function (item) {
1172                         if (item.stat_cat_entries()) {
1173                             if (item.stat_cat_entries().length > 0) {
1174                                 var right_sc = item.stat_cat_entries().filter(function (e) {
1175                                     return e.stat_cat() == sc.id() && !Boolean(e.isdeleted());
1176                                 });
1177
1178                                 if (right_sc.length > 0) {
1179                                     value_hash[right_sc[0].stat_cat_entry()] = right_sc[0].stat_cat_entry();
1180                                 } else {
1181                                     none = true;
1182                                 }
1183                             }
1184                         } else {
1185                             none = true;
1186                         }
1187                     });
1188
1189                     if (!none && Object.keys(value_hash).length == 1) {
1190                         $scope.working.statcats[sc.id()] = value_hash[Object.keys(value_hash)[0]];
1191                     } else {
1192                         $scope.working.statcats[sc.id()] = undefined;
1193                     }
1194                 });
1195
1196             } else {
1197                 $scope.clearWorking();
1198             }
1199
1200         }
1201
1202         $scope.$watch('data.copies.length', function () {
1203             if ($scope.data.copies) {
1204                 var base_orgs = $scope.data.copies.map(function(cp){
1205                     return cp.circ_lib()
1206                 }).concat(
1207                     $scope.data.copies.map(function(cp){
1208                         return cp.call_number().owning_lib()
1209                     })
1210                 ).concat(
1211                     [egCore.auth.user().ws_ou()]
1212                 ).filter(function(e,i,a){
1213                     return a.lastIndexOf(e) === i;
1214                 });
1215
1216                 var all_orgs = [];
1217                 angular.forEach(base_orgs, function(o) {
1218                     all_orgs = all_orgs.concat( egCore.org.fullPath(o, true) );
1219                 });
1220
1221                 var final_orgs = all_orgs.filter(function(e,i,a){
1222                     return a.lastIndexOf(e) === i;
1223                 }).sort(function(a, b){return parseInt(a)-parseInt(b)});
1224
1225                 if ($scope.location_orgs.toString() != final_orgs.toString()) {
1226                     $scope.location_orgs = final_orgs;
1227                     if ($scope.location_orgs.length) {
1228                         itemSvc.get_locations($scope.location_orgs).then(function(list){
1229                             angular.forEach(list, function(l) {
1230                                 $scope.location_cache[ ''+l.id() ] = l;
1231                             });
1232                             $scope.location_list = list;
1233                         });
1234
1235                         $scope.statcat_filter_list = [];
1236                         angular.forEach($scope.location_orgs, function (o) {
1237                             $scope.statcat_filter_list.push(egCore.org.get(o));
1238                         });
1239
1240                         itemSvc.get_statcats($scope.location_orgs).then(function(list){
1241                             $scope.statcats = list;
1242                             angular.forEach($scope.statcats, function (s) {
1243
1244                                 if (!$scope.working)
1245                                     $scope.working = { statcats: {}, statcat_filter: undefined};
1246                                 if (!$scope.working.statcats)
1247                                     $scope.working.statcats = {};
1248
1249                                 if (!$scope.in_item_select) {
1250                                     $scope.working.statcats[s.id()] = undefined;
1251                                 }
1252                                 createStatcatUpdateWatcher(s.id());
1253                             });
1254                             $scope.in_item_select = false;
1255                         });
1256                     }
1257                 }
1258             }
1259
1260             $scope.workingGridDataProvider.refresh();
1261         });
1262
1263         $scope.suffix_list = [];
1264         itemSvc.get_suffixes(egCore.auth.user().ws_ou()).then(function(list){
1265             $scope.suffix_list = list;
1266         });
1267
1268         $scope.prefix_list = [];
1269         itemSvc.get_prefixes(egCore.auth.user().ws_ou()).then(function(list){
1270             $scope.prefix_list = list;
1271         });
1272
1273         $scope.classification_list = [];
1274         itemSvc.get_classifications().then(function(list){
1275             $scope.classification_list = list;
1276         });
1277
1278         $scope.$watch('completed_copies.length', function () {
1279             $scope.completedGridDataProvider.refresh();
1280         });
1281
1282         $scope.location_list = [];
1283         itemSvc.get_locations().then(function(list){
1284             $scope.location_list = list;
1285         });
1286         createSimpleUpdateWatcher('location');
1287
1288         $scope.status_list = [];
1289         itemSvc.get_statuses().then(function(list){
1290             $scope.status_list = list;
1291         });
1292         createSimpleUpdateWatcher('status');
1293
1294         $scope.circ_modifier_list = [];
1295         itemSvc.get_circ_mods().then(function(list){
1296             $scope.circ_modifier_list = list;
1297         });
1298         createSimpleUpdateWatcher('circ_modifier');
1299
1300         $scope.circ_type_list = [];
1301         itemSvc.get_circ_types().then(function(list){
1302             $scope.circ_type_list = list;
1303         });
1304         createSimpleUpdateWatcher('circ_as_type');
1305
1306         $scope.age_protect_list = [];
1307         itemSvc.get_age_protects().then(function(list){
1308             $scope.age_protect_list = list;
1309         });
1310         createSimpleUpdateWatcher('age_protect');
1311
1312         createSimpleUpdateWatcher('circ_lib');
1313         createSimpleUpdateWatcher('circulate');
1314         createSimpleUpdateWatcher('holdable');
1315         createSimpleUpdateWatcher('fine_level');
1316         createSimpleUpdateWatcher('loan_duration');
1317         createSimpleUpdateWatcher('price');
1318         createSimpleUpdateWatcher('cost');
1319         createSimpleUpdateWatcher('deposit');
1320         createSimpleUpdateWatcher('deposit_amount');
1321         createSimpleUpdateWatcher('mint_condition');
1322         createSimpleUpdateWatcher('opac_visible');
1323         createSimpleUpdateWatcher('ref');
1324
1325         $scope.saveCompletedCopies = function (and_exit) {
1326             var cnHash = {};
1327             var perCnCopies = {};
1328             angular.forEach( $scope.completed_copies, function (cp) {
1329                 var cn = cp.call_number();
1330                 var cn_cps = cp.call_number().copies();
1331                 cp.call_number().copies([]);
1332                 var cn_id = cp.call_number().id();
1333                 cp.call_number(cn_id); // prevent loops in JSON-ification
1334                 if (!cnHash[cn_id]) {
1335                     cnHash[cn_id] = egCore.idl.Clone(cn);
1336                     perCnCopies[cn_id] = [egCore.idl.Clone(cp)];
1337                 } else {
1338                     perCnCopies[cn_id].push(egCore.idl.Clone(cp));
1339                 }
1340                 cp.call_number(cn); // put the data back
1341                 cp.call_number().copies(cn_cps);
1342                 if (typeof cnHash[cn_id].prefix() == 'object')
1343                     cnHash[cn_id].prefix(cnHash[cn_id].prefix().id()); // un-object-ize some fields
1344                 if (typeof cnHash[cn_id].suffix() == 'object')
1345                     cnHash[cn_id].suffix(cnHash[cn_id].suffix().id()); // un-object-ize some fields
1346             });
1347
1348             angular.forEach(perCnCopies, function (v, k) {
1349                 cnHash[k].copies(v);
1350             });
1351
1352             cnList = [];
1353             angular.forEach(cnHash, function (v, k) {
1354                 cnList.push(v);
1355             });
1356
1357             egNet.request(
1358                 'open-ils.cat',
1359                 'open-ils.cat.asset.volume.fleshed.batch.update.override',
1360                 egCore.auth.token(), cnList, 1, { auto_merge_vols : 1, create_parts : 1 }
1361             ).then(function(update_count) {
1362                 if (and_exit) {
1363                     $scope.dirty = false;
1364                     $timeout(function(){$window.close()});
1365                 }
1366             });
1367         }
1368
1369         $scope.saveAndContinue = function () {
1370             $scope.saveCompletedCopies(false);
1371         }
1372
1373         $scope.workingSaveAndExit = function () {
1374             $scope.workingToComplete();
1375             $scope.saveAndExit();
1376         }
1377
1378         $scope.saveAndExit = function () {
1379             $scope.saveCompletedCopies(true);
1380         }
1381
1382     }
1383
1384     $scope.copy_notes_dialog = function(copy_list) {
1385         var default_pub = Boolean($scope.defaults.copy_notes_pub);
1386         if (!angular.isArray(copy_list)) copy_list = [copy_list];
1387
1388         return $modal.open({
1389             templateUrl: './cat/volcopy/t_copy_notes',
1390             animation: true,
1391             controller:
1392                    ['$scope','$modalInstance',
1393             function($scope , $modalInstance) {
1394                 $scope.focusNote = true;
1395                 $scope.note = {
1396                     creator : egCore.auth.user().id(),
1397                     title   : '',
1398                     value   : '',
1399                     pub     : default_pub,
1400                 };
1401
1402                 $scope.require_initials = false;
1403                 egCore.org.settings([
1404                     'ui.staff.require_initials.copy_notes'
1405                 ]).then(function(set) {
1406                     $scope.require_initials = Boolean(set['ui.staff.require_initials.copy_notes']);
1407                 });
1408
1409                 $scope.note_list = [];
1410                 if (copy_list.length == 1) {
1411                     $scope.note_list = copy_list[0].notes();
1412                 }
1413
1414                 $scope.ok = function(note) {
1415
1416                     if (note.initials) note.value += ' [' + note.initials + ']';
1417                     angular.forEach(copy_list, function (cp) {
1418                         if (!angular.isArray(cp.notes())) cp.notes([]);
1419                         var n = new egCore.idl.acpn();
1420                         n.isnew(1);
1421                         n.creator(note.creator);
1422                         n.pub(note.pub);
1423                         n.title(note.title);
1424                         n.value(note.value);
1425                         n.owning_copy(cp.id());
1426                         cp.notes().push( n );
1427                     });
1428
1429                     $modalInstance.close();
1430                 }
1431
1432                 $scope.cancel = function($event) {
1433                     $modalInstance.dismiss();
1434                     $event.preventDefault();
1435                 }
1436             }]
1437         });
1438     }
1439
1440 }])
1441
1442 .directive("egVolTemplate", function () {
1443     return {
1444         restrict: 'E',
1445         replace: true,
1446         template: '<div ng-include="'+"'/eg/staff/cat/volcopy/t_attr_edit'"+'"></div>',
1447         scope: { },
1448         controller : ['$scope','$window','itemSvc','egCore',
1449             function ( $scope , $window , itemSvc , egCore ) {
1450
1451                 $scope.defaults = { // If defaults are not set at all, allow everything
1452                     barcode_checkdigit : false,
1453                     auto_gen_barcode : false,
1454                     statcats : true,
1455                     copy_notes : true,
1456                     attributes : {
1457                         status : true,
1458                         loan_duration : true,
1459                         fine_level : true,
1460                         cost : true,
1461                         alerts : true,
1462                         deposit : true,
1463                         deposit_amount : true,
1464                         opac_visible : true,
1465                         price : true,
1466                         circulate : true,
1467                         mint_condition : true,
1468                         circ_lib : true,
1469                         ref : true,
1470                         circ_modifier : true,
1471                         circ_as_type : true,
1472                         location : true,
1473                         holdable : true,
1474                         age_protect : true
1475                     }
1476                 };
1477
1478                 $scope.fetchDefaults = function () {
1479                     egCore.hatch.getItem('cat.copy.defaults').then(function(t) {
1480                         if (t) {
1481                             $scope.defaults = t;
1482                             $scope.working.statcat_filter = $scope.defaults.statcat_filter;
1483                         }
1484                     });
1485                 }
1486                 $scope.fetchDefaults();
1487
1488                 $scope.dirty = false;
1489                 $scope.$watch('dirty',
1490                     function(newVal, oldVal) {
1491                         if (newVal && newVal != oldVal) {
1492                             $($window).on('beforeunload.template', function(){
1493                                 return 'There is unsaved template data!'
1494                             });
1495                         } else {
1496                             $($window).off('beforeunload.template');
1497                         }
1498                     }
1499                 );
1500
1501                 $scope.template_controls = true;
1502
1503                 $scope.fetchTemplates = function () {
1504                     egCore.hatch.getItem('cat.copy.templates').then(function(t) {
1505                         if (t) {
1506                             $scope.templates = t;
1507                             $scope.template_name_list = Object.keys(t);
1508                         }
1509                     });
1510                 }
1511                 $scope.fetchTemplates();
1512             
1513                 $scope.applyTemplate = function (n) {
1514                     angular.forEach($scope.templates[n], function (v,k) {
1515                         if (k == 'circ_lib') {
1516                             $scope.working[k] = egCore.org.get(v);
1517                         } else if (!angular.isObject(v)) {
1518                             $scope.working[k] = angular.copy(v);
1519                         } else {
1520                             angular.forEach(v, function (sv,sk) {
1521                                 $scope.working[k][sk] = angular.copy(sv);
1522                             });
1523                         }
1524                     });
1525                     $scope.template_name = '';
1526                 }
1527
1528                 $scope.deleteTemplate = function (n) {
1529                     if (n) {
1530                         delete $scope.templates[n]
1531                         $scope.template_name_list = Object.keys($scope.templates);
1532                         $scope.template_name = '';
1533                         egCore.hatch.setItem('cat.copy.templates', $scope.templates);
1534                         $scope.$parent.fetchTemplates();
1535                     }
1536                 }
1537
1538                 $scope.saveTemplate = function (n) {
1539                     if (n) {
1540                         var tmpl = {};
1541             
1542                         angular.forEach($scope.working, function (v,k) {
1543                             if (angular.isObject(v)) { // we'll use the pkey
1544                                 if (v.id) v = v.id();
1545                                 else if (v.code) v = v.code();
1546                             }
1547             
1548                             tmpl[k] = v;
1549                         });
1550             
1551                         $scope.templates[n] = tmpl;
1552                         $scope.template_name_list = Object.keys($scope.templates);
1553             
1554                         egCore.hatch.setItem('cat.copy.templates', $scope.templates);
1555                         $scope.$parent.fetchTemplates();
1556
1557                         $scope.dirty = false;
1558                     }
1559                 }
1560             
1561                 $scope.templates = {};
1562                 $scope.template_name = '';
1563                 $scope.template_name_list = [];
1564             
1565                 $scope.tracker = function (x,f) { if (x) return x[f]() };
1566                 $scope.idTracker = function (x) { if (x) return $scope.tracker(x,'id') };
1567                 $scope.cant_have_vols = function (id) { return !egCore.org.CanHaveVolumes(id); };
1568             
1569                 $scope.orgById = function (id) { return egCore.org.get(id) }
1570                 $scope.statusById = function (id) {
1571                     return $scope.status_list.filter( function (s) { return s.id() == id } )[0];
1572                 }
1573                 $scope.locationById = function (id) {
1574                     return $scope.location_cache[''+id];
1575                 }
1576             
1577                 createSimpleUpdateWatcher = function (field) {
1578                     $scope.$watch('working.' + field, function () {
1579                         var newval = $scope.working[field];
1580             
1581                         if (typeof newval != 'undefined') {
1582                             $scope.dirty = true;
1583                             if (angular.isObject(newval)) { // we'll use the pkey
1584                                 if (newval.id) $scope.working[field] = newval.id();
1585                                 else if (newval.code) $scope.working[field] = newval.code();
1586                             }
1587             
1588                             if (""+newval == "" || newval == null) {
1589                                 $scope.working[field] = undefined;
1590                             }
1591             
1592                         }
1593                     });
1594                 }
1595             
1596                 $scope.working = {
1597                     statcats: {},
1598                     statcat_filter: undefined
1599                 };
1600             
1601                 createStatcatUpdateWatcher = function (id) {
1602                     return $scope.$watch('working.statcats[' + id + ']', function () {
1603                         if ($scope.working.statcats) {
1604                             var newval = $scope.working.statcats[id];
1605                 
1606                             if (typeof newval != 'undefined') {
1607                                 $scope.dirty = true;
1608                                 if (angular.isObject(newval)) { // we'll use the pkey
1609                                     newval = newval.id();
1610                                 }
1611                 
1612                                 if (""+newval == "" || newval == null) {
1613                                     $scope.working.statcats[id] = undefined;
1614                                     newval = null;
1615                                 }
1616                 
1617                             }
1618                         }
1619                     });
1620                 }
1621
1622                 $scope.clearWorking = function () {
1623                     angular.forEach($scope.working, function (v,k,o) {
1624                         if (!angular.isObject(v)) {
1625                             if (typeof v != 'undefined')
1626                                 $scope.working[k] = undefined;
1627                         } else if (k != 'circ_lib') {
1628                             angular.forEach(v, function (sv,sk) {
1629                                 $scope.working[k][sk] = undefined;
1630                             });
1631                         }
1632                     });
1633                     $scope.working.circ_lib = undefined; // special
1634                     $scope.dirty = false;
1635                 }
1636
1637                 $scope.working = {};
1638                 $scope.location_orgs = [];
1639                 $scope.location_cache = {};
1640             
1641                 $scope.location_list = [];
1642                 itemSvc.get_locations(
1643                     egCore.org.fullPath( egCore.auth.user().ws_ou(), true )
1644                 ).then(function(list){
1645                     $scope.location_list = list;
1646                 });
1647                 createSimpleUpdateWatcher('location');
1648
1649                 $scope.statcat_filter_list = egCore.org.fullPath( egCore.auth.user().ws_ou() );
1650
1651                 $scope.statcats = [];
1652                 itemSvc.get_statcats(
1653                     egCore.org.fullPath( egCore.auth.user().ws_ou(), true )
1654                 ).then(function(list){
1655                     $scope.statcats = list;
1656                     angular.forEach($scope.statcats, function (s) {
1657
1658                         if (!$scope.working)
1659                             $scope.working = { statcats: {}, statcat_filter: undefined};
1660                         if (!$scope.working.statcats)
1661                             $scope.working.statcats = {};
1662
1663                         $scope.working.statcats[s.id()] = undefined;
1664                         createStatcatUpdateWatcher(s.id());
1665                     });
1666                 });
1667             
1668                 $scope.status_list = [];
1669                 itemSvc.get_statuses().then(function(list){
1670                     $scope.status_list = list;
1671                 });
1672                 createSimpleUpdateWatcher('status');
1673             
1674                 $scope.circ_modifier_list = [];
1675                 itemSvc.get_circ_mods().then(function(list){
1676                     $scope.circ_modifier_list = list;
1677                 });
1678                 createSimpleUpdateWatcher('circ_modifier');
1679             
1680                 $scope.circ_type_list = [];
1681                 itemSvc.get_circ_types().then(function(list){
1682                     $scope.circ_type_list = list;
1683                 });
1684                 createSimpleUpdateWatcher('circ_as_type');
1685             
1686                 $scope.age_protect_list = [];
1687                 itemSvc.get_age_protects().then(function(list){
1688                     $scope.age_protect_list = list;
1689                 });
1690                 createSimpleUpdateWatcher('age_protect');
1691             
1692                 createSimpleUpdateWatcher('circulate');
1693                 createSimpleUpdateWatcher('holdable');
1694                 createSimpleUpdateWatcher('fine_level');
1695                 createSimpleUpdateWatcher('loan_duration');
1696                 createSimpleUpdateWatcher('cost');
1697                 createSimpleUpdateWatcher('deposit');
1698                 createSimpleUpdateWatcher('deposit_amount');
1699                 createSimpleUpdateWatcher('mint_condition');
1700                 createSimpleUpdateWatcher('opac_visible');
1701                 createSimpleUpdateWatcher('ref');
1702
1703                 $scope.suffix_list = [];
1704                 itemSvc.get_suffixes(egCore.auth.user().ws_ou()).then(function(list){
1705                     $scope.suffix_list = list;
1706                 });
1707
1708                 $scope.prefix_list = [];
1709                 itemSvc.get_prefixes(egCore.auth.user().ws_ou()).then(function(list){
1710                     $scope.prefix_list = list;
1711                 });
1712
1713                 $scope.classification_list = [];
1714                 itemSvc.get_classifications().then(function(list){
1715                     $scope.classification_list = list;
1716                 });
1717
1718                 createSimpleUpdateWatcher('working.callnumber.classification');
1719                 createSimpleUpdateWatcher('working.callnumber.prefix');
1720                 createSimpleUpdateWatcher('working.callnumber.suffix');
1721             }
1722         ]
1723     }
1724 })
1725
1726