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