9bdec0beba1023a3cbcaa8d995f6f1c535cdcdfe
[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                         }
665                     } else if (n < o && n >= $scope.orig_cn_count) { // removing
666                         var how_many = o - n;
667                         var list = Object
668                                 .keys($scope.struct)
669                                 .sort(function(a, b){return parseInt(a)-parseInt(b)})
670                                 .filter(function(x){ return parseInt(x) <= 0 });
671                         for (var i = 0; i < how_many; i++) {
672                             // Trimming the global list is a bit more tricky
673                             angular.forEach($scope.struct[list[i]], function (d) {
674                                 angular.forEach( $scope.allcopies, function (l, j) { 
675                                     if (l === d) $scope.allcopies.splice(j,1);
676                                 });
677                             });
678                             delete $scope.struct[list[i]];
679                         }
680                     }
681                 });
682             }
683         ]
684
685     }
686 })
687
688 /**
689  * Edit controller!
690  */
691 .controller('EditCtrl', 
692        ['$scope','$q','$window','$routeParams','$location','$timeout','egCore','egNet','egGridDataProvider','itemSvc','$modal',
693 function($scope , $q , $window , $routeParams , $location , $timeout , egCore , egNet , egGridDataProvider , itemSvc , $modal) {
694
695     $scope.defaults = { // If defaults are not set at all, allow everything
696         barcode_checkdigit : false,
697         auto_gen_barcode : false,
698         statcats : true,
699         copy_notes : true,
700         attributes : {
701             status : true,
702             loan_duration : true,
703             fine_level : true,
704             cost : true,
705             alerts : true,
706             deposit : true,
707             deposit_amount : true,
708             opac_visible : true,
709             price : true,
710             circulate : true,
711             mint_condition : true,
712             circ_lib : true,
713             ref : true,
714             circ_modifier : true,
715             circ_as_type : true,
716             location : true,
717             holdable : true,
718             age_protect : true,
719             floating : true
720         }
721     };
722
723     $scope.embedded = ($routeParams.mode && $routeParams.mode == 'embedded') ? true : false;
724
725     $scope.saveDefaults = function () {
726         egCore.hatch.setItem('cat.copy.defaults', $scope.defaults);
727     }
728
729     $scope.fetchDefaults = function () {
730         egCore.hatch.getItem('cat.copy.defaults').then(function(t) {
731             if (t) {
732                 $scope.defaults = t;
733                 if (!$scope.batch) $scope.batch = {};
734                 $scope.batch.classification = $scope.defaults.classification;
735                 $scope.batch.prefix = $scope.defaults.prefix;
736                 $scope.batch.suffix = $scope.defaults.suffix;
737                 $scope.working.statcat_filter = $scope.defaults.statcat_filter;
738                 if ($scope.defaults.always_volumes) $scope.show_vols = true;
739                 if ($scope.defaults.barcode_checkdigit) itemSvc.barcode_checkdigit = true;
740                 if ($scope.defaults.auto_gen_barcode) itemSvc.auto_gen_barcode = true;
741             }
742         });
743     }
744     $scope.fetchDefaults();
745
746     $scope.$watch('defaults.auto_gen_barcode', function (n,o) {
747         itemSvc.auto_gen_barcode = n
748     });
749
750     $scope.$watch('defaults.barcode_checkdigit', function (n,o) {
751         itemSvc.barcode_checkdigit = n
752     });
753
754     $scope.dirty = false;
755     $scope.$watch('dirty',
756         function(newVal, oldVal) {
757             if (newVal && newVal != oldVal) {
758                 $($window).on('beforeunload.edit', function(){
759                     return 'There is unsaved data!'
760                 });
761             } else {
762                 $($window).off('beforeunload.edit');
763             }
764         }
765     );
766
767     $scope.only_vols = false;
768     $scope.show_vols = true;
769     $scope.show_copies = true;
770
771     $scope.tracker = function (x,f) { if (x) return x[f]() };
772     $scope.idTracker = function (x) { if (x) return $scope.tracker(x,'id') };
773     $scope.cant_have_vols = function (id) { return !egCore.org.CanHaveVolumes(id); };
774
775     $scope.orgById = function (id) { return egCore.org.get(id) }
776     $scope.statusById = function (id) {
777         return $scope.status_list.filter( function (s) { return s.id() == id } )[0];
778     }
779     $scope.locationById = function (id) {
780         return $scope.location_cache[''+id];
781     }
782
783     $scope.workingToComplete = function () {
784         angular.forEach( $scope.workingGridControls.selectedItems(), function (c) {
785             angular.forEach( itemSvc.copies, function (w, i) {
786                 if (c === w)
787                     $scope.completed_copies = $scope.completed_copies.concat(itemSvc.copies.splice(i,1));
788             });
789         });
790
791         return true;
792     }
793
794     $scope.completeToWorking = function () {
795         angular.forEach( $scope.completedGridControls.selectedItems(), function (c) {
796             angular.forEach( $scope.completed_copies, function (w, i) {
797                 if (c === w)
798                     itemSvc.copies = itemSvc.copies.concat($scope.completed_copies.splice(i,1));
799             });
800         });
801
802         return true;
803     }
804
805     createSimpleUpdateWatcher = function (field) {
806         return $scope.$watch('working.' + field, function () {
807             var newval = $scope.working[field];
808
809             if (typeof newval != 'undefined') {
810                 if (angular.isObject(newval)) { // we'll use the pkey
811                     if (newval.id) newval = newval.id();
812                     else if (newval.code) newval = newval.code();
813                 }
814
815                 if (""+newval == "" || newval == null) {
816                     $scope.working[field] = undefined;
817                     newval = null;
818                 }
819
820                 if ($scope.workingGridControls && $scope.workingGridControls.selectedItems) {
821                     angular.forEach(
822                         $scope.workingGridControls.selectedItems(),
823                         function (cp) {
824                             if (cp[field]() !== newval) {
825                                 cp[field](newval);
826                                 cp.ischanged(1);
827                                 $scope.dirty = true;
828                             }
829                         }
830                     );
831                 }
832             }
833         });
834     }
835
836     $scope.working = {
837         statcats: {},
838         statcat_filter: undefined
839     };
840
841     $scope.statcatUpdate = function (id) {
842         var newval = $scope.working.statcats[id];
843
844         if (typeof newval != 'undefined') {
845             if (angular.isObject(newval)) { // we'll use the pkey
846                 newval = newval.id();
847             }
848     
849             if (""+newval == "" || newval == null) {
850                 $scope.working.statcats[id] = undefined;
851                 newval = null;
852             }
853     
854             if (!$scope.in_item_select && $scope.workingGridControls && $scope.workingGridControls.selectedItems) {
855                 angular.forEach(
856                     $scope.workingGridControls.selectedItems(),
857                     function (cp) {
858                         $scope.dirty = true;
859
860                         cp.stat_cat_entries(
861                             angular.forEach( cp.stat_cat_entries(), function (e) {
862                                 if (e.stat_cat() == id) { // mark deleted
863                                     e.isdeleted(1);
864                                 }
865                             })
866                         );
867     
868                         if (newval) {
869                             var e = new egCore.idl.ascecm();
870                             e.isnew( 1 );
871                             e.owning_copy( cp.id() );
872                             e.stat_cat( id );
873                             e.stat_cat_entry( newval );
874
875                             cp.stat_cat_entries(
876                                 cp.stat_cat_entries().concat([ e ])
877                             );
878
879                         }
880
881                         cp.stat_cat_entries( // trim out ephemeral deleted ones
882                             cp.stat_cat_entries().filter(function (e) {
883                                 if (Boolean(e.isnew())) {
884                                     if (Boolean(e.isdeleted())) {
885                                         return false;
886                                     }
887                                 }
888                                 return true;
889                             })
890                         );
891    
892                         cp.ischanged(1);
893                     }
894                 );
895             }
896         }
897     }
898
899     var dataKey = $routeParams.dataKey;
900     console.debug('dataKey: ' + dataKey);
901
902     if (dataKey && dataKey.length > 0) {
903
904         $scope.templates = {};
905         $scope.template_name = '';
906         $scope.template_name_list = [];
907
908         $scope.fetchTemplates = function () {
909             egCore.hatch.getItem('cat.copy.templates').then(function(t) {
910                 if (t) {
911                     $scope.templates = t;
912                     $scope.template_name_list = Object.keys(t);
913                 }
914             });
915             egCore.hatch.getItem('cat.copy.last_template').then(function(t) {
916                 if (t) $scope.template_name = t;
917             });
918         }
919         $scope.fetchTemplates();
920
921         $scope.applyTemplate = function (n) {
922             angular.forEach($scope.templates[n], function (v,k) {
923                 if (k == 'circ_lib') {
924                     $scope.working[k] = egCore.org.get(v);
925                 } else if (!angular.isObject(v)) {
926                     $scope.working[k] = angular.copy(v);
927                 } else {
928                     angular.forEach(v, function (sv,sk) {
929                         if (k == 'callnumber') {
930                             angular.forEach(v, function (cnv,cnk) {
931                                 $scope.batch[cnk] = cnv;
932                             });
933                             $scope.applyBatchCNValues();
934                         } else {
935                             $scope.working[k][sk] = angular.copy(sv);
936                             if (k == 'statcats') $scope.statcatUpdate(sk);
937                         }
938                     });
939                 }
940             });
941             egCore.hatch.setItem('cat.copy.last_template', n);
942         }
943
944         $scope.copytab = 'working';
945         $scope.tab = 'edit';
946         $scope.summaryRecord = null;
947         $scope.record_id = null;
948         $scope.data = {};
949         $scope.completed_copies = [];
950         $scope.location_orgs = [];
951         $scope.location_cache = {};
952         $scope.statcats = [];
953         if (!$scope.batch) $scope.batch = {};
954
955         $scope.applyBatchCNValues = function () {
956             if ($scope.data.tree) {
957                 angular.forEach($scope.data.tree, function(cn_hash) {
958                     angular.forEach(cn_hash, function(copies) {
959                         angular.forEach(copies, function(cp) {
960                             if (typeof $scope.batch.classification != 'undefined' && $scope.batch.classification != '') {
961                                 var label_class = $scope.classification_list.filter(function(p){ return p.id() == $scope.batch.classification })[0];
962                                 cp.call_number().label_class(label_class);
963                                 cp.call_number().ischanged(1);
964                                 $scope.dirty = true;
965                             }
966                             if (typeof $scope.batch.prefix != 'undefined' && $scope.batch.prefix != '') {
967                                 var prefix = $scope.prefix_list.filter(function(p){ return p.id() == $scope.batch.prefix })[0];
968                                 cp.call_number().prefix(prefix);
969                                 cp.call_number().ischanged(1);
970                                 $scope.dirty = true;
971                             }
972                             if (typeof $scope.batch.label != 'undefined' && $scope.batch.label != '') {
973                                 cp.call_number().label($scope.batch.label);
974                                 cp.call_number().ischanged(1);
975                                 $scope.dirty = true;
976                             }
977                             if (typeof $scope.batch.suffix != 'undefined' && $scope.batch.suffix != '') {
978                                 var suffix = $scope.suffix_list.filter(function(p){ return p.id() == $scope.batch.suffix })[0];
979                                 cp.call_number().suffix(suffix);
980                                 cp.call_number().ischanged(1);
981                                 $scope.dirty = true;
982                             }
983                         });
984                     });
985                 });
986             }
987         }
988
989         $scope.clearWorking = function () {
990             angular.forEach($scope.working, function (v,k,o) {
991                 if (!angular.isObject(v)) {
992                     if (typeof v != 'undefined')
993                         $scope.working[k] = undefined;
994                 } else if (k != 'circ_lib') {
995                     angular.forEach(v, function (sv,sk) {
996                         if (typeof v != 'undefined')
997                             $scope.working[k][sk] = undefined;
998                     });
999                 }
1000             });
1001             $scope.working.circ_lib = undefined; // special
1002         }
1003
1004         $scope.completedGridDataProvider = egGridDataProvider.instance({
1005             get : function(offset, count) {
1006                 //return provider.arrayNotifier(itemSvc.copies, offset, count);
1007                 return this.arrayNotifier($scope.completed_copies, offset, count);
1008             }
1009         });
1010
1011         $scope.completedGridControls = {};
1012
1013         $scope.workingGridDataProvider = egGridDataProvider.instance({
1014             get : function(offset, count) {
1015                 //return provider.arrayNotifier(itemSvc.copies, offset, count);
1016                 return this.arrayNotifier(itemSvc.copies, offset, count);
1017             }
1018         });
1019
1020         $scope.workingGridControls = {};
1021         $scope.add_vols_copies = false;
1022         $scope.is_fast_add = false;
1023
1024         egNet.request(
1025             'open-ils.actor',
1026             'open-ils.actor.anon_cache.get_value',
1027             dataKey, 'edit-these-copies'
1028         ).then(function (data) {
1029
1030             if (data) {
1031                 if (data.hide_vols && !$scope.defaults.always_volumes) $scope.show_vols = false;
1032                 if (data.hide_copies) {
1033                     $scope.show_copies = false;
1034                     $scope.only_vols = true;
1035                 }
1036
1037                 $scope.record_id = data.record_id;
1038
1039                 function fetchRaw () {
1040                     if (!$scope.only_vols) $scope.dirty = true;
1041                     $scope.add_vols_copies = true;
1042
1043                     /* data.raw data structure looks like this:
1044                      * [{
1045                      *      callnumber : $cn_id, // optional, to add a copy to a cn
1046                      *      owner      : $org, // optional, defaults to ws_ou
1047                      *      label      : $cn_label, // optional, to supply a label on a new cn
1048                      *      barcode    : $cp_barcode // optional, to supply a barcode on a new cp
1049                      *      fast_add   : boolean // optional, to specify whether this came
1050                      *                              in as a fast add
1051                      * },...]
1052                      * 
1053                      * All can be left out and a completely empty vol/copy combo will be vivicated.
1054                      */
1055
1056                     angular.forEach(
1057                         data.raw,
1058                         function (proto) {
1059                             if (proto.fast_add) $scope.is_fast_add = true;
1060                             if (proto.callnumber) {
1061                                 return egCore.pcrud.retrieve('acn', proto.callnumber)
1062                                 .then(function(cn) {
1063                                     var cp = new egCore.idl.acp();
1064                                     cp.call_number( cn );
1065                                     cp.id( --itemSvc.new_cp_id );
1066                                     if (!$scope.only_vols) cp.isnew( true );
1067                                     cp.circ_lib( proto.owner || egCore.auth.user().ws_ou() );
1068
1069                                     cp.deposit(0);
1070                                     cp.price(0);
1071                                     cp.deposit_amount(0);
1072                                     cp.fine_level(2); // Normal
1073                                     cp.loan_duration(2); // Normal
1074                                     cp.location(1); // Stacks
1075                                     cp.circulate('t');
1076                                     cp.holdable('t');
1077                                     cp.opac_visible('t');
1078                                     cp.ref('f');
1079                                     cp.mint_condition('t');
1080
1081                                     if (proto.barcode) cp.barcode( proto.barcode );
1082
1083                                     itemSvc.addCopy(cp)
1084                                 });
1085                             } else {
1086                                 var cn = new egCore.idl.acn();
1087                                 cn.id( --itemSvc.new_cn_id );
1088                                 cn.isnew( true );
1089                                 cn.prefix( $scope.defaults.prefix || -1 );
1090                                 cn.suffix( $scope.defaults.suffix || -1 );
1091                                 cn.label_class( $scope.defaults.classification || 1 );
1092                                 cn.owning_lib( proto.owner || egCore.auth.user().ws_ou() );
1093                                 cn.record( $scope.record_id );
1094                                 if (proto.label) cn.label( proto.label );
1095
1096                                 var cp = new egCore.idl.acp();
1097                                 cp.call_number( cn );
1098                                 cp.id( --itemSvc.new_cp_id );
1099                                 cp.isnew( true );
1100
1101                                 cp.deposit(0);
1102                                 cp.price(0);
1103                                 cp.deposit_amount(0);
1104                                 cp.fine_level(2); // Normal
1105                                 cp.loan_duration(2); // Normal
1106                                 cp.location(1); // Stacks
1107                                 cp.circulate('t');
1108                                 cp.holdable('t');
1109                                 cp.opac_visible('t');
1110                                 cp.ref('f');
1111                                 cp.mint_condition('t');
1112
1113                                 cp.circ_lib( proto.owner || egCore.auth.user().ws_ou() );
1114                                 if (proto.barcode) cp.barcode( proto.barcode );
1115
1116                                 itemSvc.addCopy(cp)
1117                             }
1118     
1119                         }
1120                     );
1121
1122                     return itemSvc.copies;
1123                 }
1124
1125                 if (data.copies && data.copies.length)
1126                     return itemSvc.fetchIds(data.copies).then(fetchRaw);
1127
1128                 return fetchRaw();
1129
1130             }
1131
1132         }).then( function() {
1133             $scope.data = itemSvc;
1134             if ($scope.add_vols_copies) {
1135                 var status_setting = $scope.is_fast_add ?
1136                     'cat.default_copy_status_fast' :
1137                     'cat.default_copy_status_normal';
1138                 egCore.org.settings([
1139                     status_setting
1140                 ]).then(function(set) {
1141                     $scope.default_ccs = set[status_setting] || 
1142                         ($scope.is_fast_add ? 0 : 5); // 0 is Available, 5 is In Process
1143                     angular.forEach($scope.data.copies, function (cp) {
1144                         cp.status($scope.default_ccs);
1145                     });
1146                     $scope.workingGridDataProvider.refresh();
1147                 });
1148             }
1149         });
1150
1151         $scope.focusNextFirst = function(prev_lib,prev_bc) {
1152             var n;
1153             var yep = false;
1154             angular.forEach(Object.keys($scope.data.tree).sort(), function (lib) {
1155                 if (n) return;
1156
1157                 if (lib == prev_lib) {
1158                     yep = true;
1159                     return;
1160                 }
1161
1162                 if (yep) n = lib;
1163             });
1164
1165             if (n) {
1166                 var first_cn = Object.keys($scope.data.tree[n])[0];
1167                 var next = '#' + first_cn + '_' + $scope.data.tree[n][first_cn][0].id();
1168                 var el = $(next);
1169                 if (el) {
1170                     if (!itemSvc.currently_generating) el.focus();
1171                     if (prev_bc && itemSvc.auto_gen_barcode && el.val() == "") {
1172                         itemSvc.nextBarcode(prev_bc).then(function(bc){
1173                             el.focus();
1174                             el.val(bc);
1175                             el.trigger('change');
1176                         });
1177                     } else {
1178                         itemSvc.currently_generating = false;
1179                     }
1180                 }
1181             }
1182         }
1183
1184         $scope.in_item_select = false;
1185         $scope.afterItemSelect = function() { $scope.in_item_select = false };
1186         $scope.handleItemSelect = function (item_list) {
1187             if (item_list && item_list.length > 0) {
1188                 $scope.in_item_select = true;
1189
1190                 angular.forEach(Object.keys($scope.defaults.attributes), function (attr) {
1191
1192                     var value_hash = {};
1193                     angular.forEach(item_list, function (item) {
1194                         if (item[attr]) {
1195                             var v = item[attr]()
1196                             if (angular.isObject(v)) {
1197                                 if (v.id) v = v.id();
1198                                 else if (v.code) v = v.code();
1199                             }
1200                             value_hash[v] = 1;
1201                         }
1202                     });
1203
1204                     if (Object.keys(value_hash).length == 1) {
1205                         if (attr == 'circ_lib') {
1206                             $scope.working[attr] = egCore.org.get(item_list[0][attr]());
1207                         } else {
1208                             $scope.working[attr] = item_list[0][attr]();
1209                         }
1210                     } else {
1211                         $scope.working[attr] = undefined;
1212                     }
1213                 });
1214
1215                 angular.forEach($scope.statcats, function (sc) {
1216
1217                     var counter = -1;
1218                     var value_hash = {};
1219                     var none = false;
1220                     angular.forEach(item_list, function (item) {
1221                         if (item.stat_cat_entries()) {
1222                             if (item.stat_cat_entries().length > 0) {
1223                                 var right_sc = item.stat_cat_entries().filter(function (e) {
1224                                     return e.stat_cat() == sc.id() && !Boolean(e.isdeleted());
1225                                 });
1226
1227                                 if (right_sc.length > 0) {
1228                                     value_hash[right_sc[0].stat_cat_entry()] = right_sc[0].stat_cat_entry();
1229                                 } else {
1230                                     none = true;
1231                                 }
1232                             }
1233                         } else {
1234                             none = true;
1235                         }
1236                     });
1237
1238                     if (!none && Object.keys(value_hash).length == 1) {
1239                         $scope.working.statcats[sc.id()] = value_hash[Object.keys(value_hash)[0]];
1240                     } else {
1241                         $scope.working.statcats[sc.id()] = undefined;
1242                     }
1243                 });
1244
1245             } else {
1246                 $scope.clearWorking();
1247             }
1248
1249         }
1250
1251         $scope.$watch('data.copies.length', function () {
1252             if ($scope.data.copies) {
1253                 var base_orgs = $scope.data.copies.map(function(cp){
1254                     return cp.circ_lib()
1255                 }).concat(
1256                     $scope.data.copies.map(function(cp){
1257                         return cp.call_number().owning_lib()
1258                     })
1259                 ).concat(
1260                     [egCore.auth.user().ws_ou()]
1261                 ).filter(function(e,i,a){
1262                     return a.lastIndexOf(e) === i;
1263                 });
1264
1265                 var all_orgs = [];
1266                 angular.forEach(base_orgs, function(o) {
1267                     all_orgs = all_orgs.concat( egCore.org.fullPath(o, true) );
1268                 });
1269
1270                 var final_orgs = all_orgs.filter(function(e,i,a){
1271                     return a.lastIndexOf(e) === i;
1272                 }).sort(function(a, b){return parseInt(a)-parseInt(b)});
1273
1274                 if ($scope.location_orgs.toString() != final_orgs.toString()) {
1275                     $scope.location_orgs = final_orgs;
1276                     if ($scope.location_orgs.length) {
1277                         itemSvc.get_locations($scope.location_orgs).then(function(list){
1278                             angular.forEach(list, function(l) {
1279                                 $scope.location_cache[ ''+l.id() ] = l;
1280                             });
1281                             $scope.location_list = list;
1282                         });
1283
1284                         $scope.statcat_filter_list = [];
1285                         angular.forEach($scope.location_orgs, function (o) {
1286                             $scope.statcat_filter_list.push(egCore.org.get(o));
1287                         });
1288
1289                         itemSvc.get_statcats($scope.location_orgs).then(function(list){
1290                             $scope.statcats = list;
1291                             angular.forEach($scope.statcats, function (s) {
1292
1293                                 if (!$scope.working)
1294                                     $scope.working = { statcats: {}, statcat_filter: undefined};
1295                                 if (!$scope.working.statcats)
1296                                     $scope.working.statcats = {};
1297
1298                                 if (!$scope.in_item_select) {
1299                                     $scope.working.statcats[s.id()] = undefined;
1300                                 }
1301                                 createStatcatUpdateWatcher(s.id());
1302                             });
1303                             $scope.in_item_select = false;
1304                         });
1305                     }
1306                 }
1307             }
1308
1309             $scope.workingGridDataProvider.refresh();
1310         });
1311
1312         $scope.statcat_visible = function (sc_owner) {
1313             var visible = typeof $scope.working.statcat_filter === 'undefined' || !$scope.working.statcat_filter;
1314             angular.forEach(egCore.org.ancestors(sc_owner), function (anscestor_org) {
1315                 if ($scope.working.statcat_filter == anscestor_org.id())
1316                     visible = true;
1317             });
1318             return visible;
1319         }
1320
1321         $scope.suffix_list = [];
1322         itemSvc.get_suffixes(egCore.auth.user().ws_ou()).then(function(list){
1323             $scope.suffix_list = list;
1324         });
1325
1326         $scope.prefix_list = [];
1327         itemSvc.get_prefixes(egCore.auth.user().ws_ou()).then(function(list){
1328             $scope.prefix_list = list;
1329         });
1330
1331         $scope.classification_list = [];
1332         itemSvc.get_classifications().then(function(list){
1333             $scope.classification_list = list;
1334         });
1335
1336         $scope.$watch('completed_copies.length', function () {
1337             $scope.completedGridDataProvider.refresh();
1338         });
1339
1340         $scope.location_list = [];
1341         itemSvc.get_locations().then(function(list){
1342             $scope.location_list = list;
1343         });
1344         createSimpleUpdateWatcher('location');
1345
1346         $scope.status_list = [];
1347         itemSvc.get_statuses().then(function(list){
1348             $scope.status_list = list;
1349         });
1350         createSimpleUpdateWatcher('status');
1351
1352         $scope.circ_modifier_list = [];
1353         itemSvc.get_circ_mods().then(function(list){
1354             $scope.circ_modifier_list = list;
1355         });
1356         createSimpleUpdateWatcher('circ_modifier');
1357
1358         $scope.circ_type_list = [];
1359         itemSvc.get_circ_types().then(function(list){
1360             $scope.circ_type_list = list;
1361         });
1362         createSimpleUpdateWatcher('circ_as_type');
1363
1364         $scope.age_protect_list = [];
1365         itemSvc.get_age_protects().then(function(list){
1366             $scope.age_protect_list = list;
1367         });
1368         createSimpleUpdateWatcher('age_protect');
1369
1370         $scope.floating_list = [];
1371         itemSvc.get_floating_groups().then(function(list){
1372             $scope.floating_list = list;
1373         });
1374         createSimpleUpdateWatcher('floating');
1375
1376         createSimpleUpdateWatcher('circ_lib');
1377         createSimpleUpdateWatcher('circulate');
1378         createSimpleUpdateWatcher('holdable');
1379         createSimpleUpdateWatcher('fine_level');
1380         createSimpleUpdateWatcher('loan_duration');
1381         createSimpleUpdateWatcher('price');
1382         createSimpleUpdateWatcher('cost');
1383         createSimpleUpdateWatcher('deposit');
1384         createSimpleUpdateWatcher('deposit_amount');
1385         createSimpleUpdateWatcher('mint_condition');
1386         createSimpleUpdateWatcher('opac_visible');
1387         createSimpleUpdateWatcher('ref');
1388
1389         $scope.saveCompletedCopies = function (and_exit) {
1390             var cnHash = {};
1391             var perCnCopies = {};
1392             angular.forEach( $scope.completed_copies, function (cp) {
1393                 var cn = cp.call_number();
1394                 var cn_cps = cp.call_number().copies();
1395                 cp.call_number().copies([]);
1396                 var cn_id = cp.call_number().id();
1397                 cp.call_number(cn_id); // prevent loops in JSON-ification
1398                 if (!cnHash[cn_id]) {
1399                     cnHash[cn_id] = egCore.idl.Clone(cn);
1400                     perCnCopies[cn_id] = [egCore.idl.Clone(cp)];
1401                 } else {
1402                     perCnCopies[cn_id].push(egCore.idl.Clone(cp));
1403                 }
1404                 cp.call_number(cn); // put the data back
1405                 cp.call_number().copies(cn_cps);
1406                 if (typeof cnHash[cn_id].prefix() == 'object')
1407                     cnHash[cn_id].prefix(cnHash[cn_id].prefix().id()); // un-object-ize some fields
1408                 if (typeof cnHash[cn_id].suffix() == 'object')
1409                     cnHash[cn_id].suffix(cnHash[cn_id].suffix().id()); // un-object-ize some fields
1410             });
1411
1412             angular.forEach(perCnCopies, function (v, k) {
1413                 cnHash[k].copies(v);
1414             });
1415
1416             cnList = [];
1417             angular.forEach(cnHash, function (v, k) {
1418                 cnList.push(v);
1419             });
1420
1421             egNet.request(
1422                 'open-ils.cat',
1423                 'open-ils.cat.asset.volume.fleshed.batch.update.override',
1424                 egCore.auth.token(), cnList, 1, { auto_merge_vols : 1, create_parts : 1 }
1425             ).then(function(update_count) {
1426                 if (and_exit) {
1427                     $scope.dirty = false;
1428                     $timeout(function(){$window.close()});
1429                 }
1430             });
1431         }
1432
1433         $scope.saveAndContinue = function () {
1434             $scope.saveCompletedCopies(false);
1435         }
1436
1437         $scope.workingSaveAndExit = function () {
1438             $scope.workingToComplete();
1439             $scope.saveAndExit();
1440         }
1441
1442         $scope.saveAndExit = function () {
1443             $scope.saveCompletedCopies(true);
1444         }
1445
1446     }
1447
1448     $scope.copy_notes_dialog = function(copy_list) {
1449         var default_pub = Boolean($scope.defaults.copy_notes_pub);
1450         if (!angular.isArray(copy_list)) copy_list = [copy_list];
1451
1452         return $modal.open({
1453             templateUrl: './cat/volcopy/t_copy_notes',
1454             animation: true,
1455             controller:
1456                    ['$scope','$modalInstance',
1457             function($scope , $modalInstance) {
1458                 $scope.focusNote = true;
1459                 $scope.note = {
1460                     creator : egCore.auth.user().id(),
1461                     title   : '',
1462                     value   : '',
1463                     pub     : default_pub,
1464                 };
1465
1466                 $scope.require_initials = false;
1467                 egCore.org.settings([
1468                     'ui.staff.require_initials.copy_notes'
1469                 ]).then(function(set) {
1470                     $scope.require_initials = Boolean(set['ui.staff.require_initials.copy_notes']);
1471                 });
1472
1473                 $scope.note_list = [];
1474                 if (copy_list.length == 1) {
1475                     $scope.note_list = copy_list[0].notes();
1476                 }
1477
1478                 $scope.ok = function(note) {
1479
1480                     if (note.initials) note.value += ' [' + note.initials + ']';
1481                     angular.forEach(copy_list, function (cp) {
1482                         if (!angular.isArray(cp.notes())) cp.notes([]);
1483                         var n = new egCore.idl.acpn();
1484                         n.isnew(1);
1485                         n.creator(note.creator);
1486                         n.pub(note.pub);
1487                         n.title(note.title);
1488                         n.value(note.value);
1489                         n.owning_copy(cp.id());
1490                         cp.notes().push( n );
1491                     });
1492
1493                     $modalInstance.close();
1494                 }
1495
1496                 $scope.cancel = function($event) {
1497                     $modalInstance.dismiss();
1498                     $event.preventDefault();
1499                 }
1500             }]
1501         });
1502     }
1503
1504 }])
1505
1506 .directive("egVolTemplate", function () {
1507     return {
1508         restrict: 'E',
1509         replace: true,
1510         template: '<div ng-include="'+"'/eg/staff/cat/volcopy/t_attr_edit'"+'"></div>',
1511         scope: { },
1512         controller : ['$scope','$window','itemSvc','egCore',
1513             function ( $scope , $window , itemSvc , egCore ) {
1514
1515                 $scope.defaults = { // If defaults are not set at all, allow everything
1516                     barcode_checkdigit : false,
1517                     auto_gen_barcode : false,
1518                     statcats : true,
1519                     copy_notes : true,
1520                     attributes : {
1521                         status : true,
1522                         loan_duration : true,
1523                         fine_level : true,
1524                         cost : true,
1525                         alerts : true,
1526                         deposit : true,
1527                         deposit_amount : true,
1528                         opac_visible : true,
1529                         price : true,
1530                         circulate : true,
1531                         mint_condition : true,
1532                         circ_lib : true,
1533                         ref : true,
1534                         circ_modifier : true,
1535                         circ_as_type : true,
1536                         location : true,
1537                         holdable : true,
1538                         age_protect : true,
1539                         floating : true
1540                     }
1541                 };
1542
1543                 $scope.fetchDefaults = function () {
1544                     egCore.hatch.getItem('cat.copy.defaults').then(function(t) {
1545                         if (t) {
1546                             $scope.defaults = t;
1547                             $scope.working.statcat_filter = $scope.defaults.statcat_filter;
1548                         }
1549                     });
1550                 }
1551                 $scope.fetchDefaults();
1552
1553                 $scope.dirty = false;
1554                 $scope.$watch('dirty',
1555                     function(newVal, oldVal) {
1556                         if (newVal && newVal != oldVal) {
1557                             $($window).on('beforeunload.template', function(){
1558                                 return 'There is unsaved template data!'
1559                             });
1560                         } else {
1561                             $($window).off('beforeunload.template');
1562                         }
1563                     }
1564                 );
1565
1566                 $scope.template_controls = true;
1567
1568                 $scope.fetchTemplates = function () {
1569                     egCore.hatch.getItem('cat.copy.templates').then(function(t) {
1570                         if (t) {
1571                             $scope.templates = t;
1572                             $scope.template_name_list = Object.keys(t);
1573                         }
1574                     });
1575                 }
1576                 $scope.fetchTemplates();
1577             
1578                 $scope.applyTemplate = function (n) {
1579                     angular.forEach($scope.templates[n], function (v,k) {
1580                         if (k == 'circ_lib') {
1581                             $scope.working[k] = egCore.org.get(v);
1582                         } else if (!angular.isObject(v)) {
1583                             $scope.working[k] = angular.copy(v);
1584                         } else {
1585                             angular.forEach(v, function (sv,sk) {
1586                                 $scope.working[k][sk] = angular.copy(sv);
1587                             });
1588                         }
1589                     });
1590                     $scope.template_name = '';
1591                 }
1592
1593                 $scope.deleteTemplate = function (n) {
1594                     if (n) {
1595                         delete $scope.templates[n]
1596                         $scope.template_name_list = Object.keys($scope.templates);
1597                         $scope.template_name = '';
1598                         egCore.hatch.setItem('cat.copy.templates', $scope.templates);
1599                         $scope.$parent.fetchTemplates();
1600                     }
1601                 }
1602
1603                 $scope.saveTemplate = function (n) {
1604                     if (n) {
1605                         var tmpl = {};
1606             
1607                         angular.forEach($scope.working, function (v,k) {
1608                             if (angular.isObject(v)) { // we'll use the pkey
1609                                 if (v.id) v = v.id();
1610                                 else if (v.code) v = v.code();
1611                             }
1612             
1613                             tmpl[k] = v;
1614                         });
1615             
1616                         $scope.templates[n] = tmpl;
1617                         $scope.template_name_list = Object.keys($scope.templates);
1618             
1619                         egCore.hatch.setItem('cat.copy.templates', $scope.templates);
1620                         $scope.$parent.fetchTemplates();
1621
1622                         $scope.dirty = false;
1623                     }
1624                 }
1625             
1626                 $scope.templates = {};
1627                 $scope.template_name = '';
1628                 $scope.template_name_list = [];
1629             
1630                 $scope.tracker = function (x,f) { if (x) return x[f]() };
1631                 $scope.idTracker = function (x) { if (x) return $scope.tracker(x,'id') };
1632                 $scope.cant_have_vols = function (id) { return !egCore.org.CanHaveVolumes(id); };
1633             
1634                 $scope.orgById = function (id) { return egCore.org.get(id) }
1635                 $scope.statusById = function (id) {
1636                     return $scope.status_list.filter( function (s) { return s.id() == id } )[0];
1637                 }
1638                 $scope.locationById = function (id) {
1639                     return $scope.location_cache[''+id];
1640                 }
1641             
1642                 createSimpleUpdateWatcher = function (field) {
1643                     $scope.$watch('working.' + field, function () {
1644                         var newval = $scope.working[field];
1645             
1646                         if (typeof newval != 'undefined') {
1647                             $scope.dirty = true;
1648                             if (angular.isObject(newval)) { // we'll use the pkey
1649                                 if (newval.id) $scope.working[field] = newval.id();
1650                                 else if (newval.code) $scope.working[field] = newval.code();
1651                             }
1652             
1653                             if (""+newval == "" || newval == null) {
1654                                 $scope.working[field] = undefined;
1655                             }
1656             
1657                         }
1658                     });
1659                 }
1660             
1661                 $scope.working = {
1662                     statcats: {},
1663                     statcat_filter: undefined
1664                 };
1665             
1666                 createStatcatUpdateWatcher = function (id) {
1667                     return $scope.$watch('working.statcats[' + id + ']', function () {
1668                         if ($scope.working.statcats) {
1669                             var newval = $scope.working.statcats[id];
1670                 
1671                             if (typeof newval != 'undefined') {
1672                                 $scope.dirty = true;
1673                                 if (angular.isObject(newval)) { // we'll use the pkey
1674                                     newval = newval.id();
1675                                 }
1676                 
1677                                 if (""+newval == "" || newval == null) {
1678                                     $scope.working.statcats[id] = undefined;
1679                                     newval = null;
1680                                 }
1681                 
1682                             }
1683                         }
1684                     });
1685                 }
1686
1687                 $scope.clearWorking = function () {
1688                     angular.forEach($scope.working, function (v,k,o) {
1689                         if (!angular.isObject(v)) {
1690                             if (typeof v != 'undefined')
1691                                 $scope.working[k] = undefined;
1692                         } else if (k != 'circ_lib') {
1693                             angular.forEach(v, function (sv,sk) {
1694                                 $scope.working[k][sk] = undefined;
1695                             });
1696                         }
1697                     });
1698                     $scope.working.circ_lib = undefined; // special
1699                     $scope.dirty = false;
1700                 }
1701
1702                 $scope.working = {};
1703                 $scope.location_orgs = [];
1704                 $scope.location_cache = {};
1705             
1706                 $scope.location_list = [];
1707                 itemSvc.get_locations(
1708                     egCore.org.fullPath( egCore.auth.user().ws_ou(), true )
1709                 ).then(function(list){
1710                     $scope.location_list = list;
1711                 });
1712                 createSimpleUpdateWatcher('location');
1713
1714                 $scope.statcat_filter_list = egCore.org.fullPath( egCore.auth.user().ws_ou() );
1715
1716                 $scope.statcats = [];
1717                 itemSvc.get_statcats(
1718                     egCore.org.fullPath( egCore.auth.user().ws_ou(), true )
1719                 ).then(function(list){
1720                     $scope.statcats = list;
1721                     angular.forEach($scope.statcats, function (s) {
1722
1723                         if (!$scope.working)
1724                             $scope.working = { statcats: {}, statcat_filter: undefined};
1725                         if (!$scope.working.statcats)
1726                             $scope.working.statcats = {};
1727
1728                         $scope.working.statcats[s.id()] = undefined;
1729                         createStatcatUpdateWatcher(s.id());
1730                     });
1731                 });
1732             
1733                 $scope.status_list = [];
1734                 itemSvc.get_statuses().then(function(list){
1735                     $scope.status_list = list;
1736                 });
1737                 createSimpleUpdateWatcher('status');
1738             
1739                 $scope.circ_modifier_list = [];
1740                 itemSvc.get_circ_mods().then(function(list){
1741                     $scope.circ_modifier_list = list;
1742                 });
1743                 createSimpleUpdateWatcher('circ_modifier');
1744             
1745                 $scope.circ_type_list = [];
1746                 itemSvc.get_circ_types().then(function(list){
1747                     $scope.circ_type_list = list;
1748                 });
1749                 createSimpleUpdateWatcher('circ_as_type');
1750             
1751                 $scope.age_protect_list = [];
1752                 itemSvc.get_age_protects().then(function(list){
1753                     $scope.age_protect_list = list;
1754                 });
1755                 createSimpleUpdateWatcher('age_protect');
1756             
1757                 createSimpleUpdateWatcher('circulate');
1758                 createSimpleUpdateWatcher('holdable');
1759                 createSimpleUpdateWatcher('fine_level');
1760                 createSimpleUpdateWatcher('loan_duration');
1761                 createSimpleUpdateWatcher('cost');
1762                 createSimpleUpdateWatcher('deposit');
1763                 createSimpleUpdateWatcher('deposit_amount');
1764                 createSimpleUpdateWatcher('mint_condition');
1765                 createSimpleUpdateWatcher('opac_visible');
1766                 createSimpleUpdateWatcher('ref');
1767
1768                 $scope.suffix_list = [];
1769                 itemSvc.get_suffixes(egCore.auth.user().ws_ou()).then(function(list){
1770                     $scope.suffix_list = list;
1771                 });
1772
1773                 $scope.prefix_list = [];
1774                 itemSvc.get_prefixes(egCore.auth.user().ws_ou()).then(function(list){
1775                     $scope.prefix_list = list;
1776                 });
1777
1778                 $scope.classification_list = [];
1779                 itemSvc.get_classifications().then(function(list){
1780                     $scope.classification_list = list;
1781                 });
1782
1783                 createSimpleUpdateWatcher('working.callnumber.classification');
1784                 createSimpleUpdateWatcher('working.callnumber.prefix');
1785                 createSimpleUpdateWatcher('working.callnumber.suffix');
1786             }
1787         ]
1788     }
1789 })
1790
1791