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