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