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