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