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