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