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