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