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