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