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