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