]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/cat/volcopy/app.js
webstaff: Add copy note creation/editing
[working/Evergreen.git] / Open-ILS / web / js / ui / default / staff / cat / volcopy / app.js
1 /**
2  * Vol/Copy Editor
3  */
4
5 angular.module('egVolCopy',
6     ['ngRoute', 'ui.bootstrap', 'egCoreMod', 'egUiMod', 'egGridMod'])
7
8 .filter('boolText', function(){
9     return function (v) {
10         return v == 't';
11     }
12 })
13
14 .config(function($routeProvider, $locationProvider, $compileProvider) {
15     $locationProvider.html5Mode(true);
16     $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|blob):/); // grid export
17
18     var resolver = {
19         delay : ['egStartup', function(egStartup) { return egStartup.go(); }]
20     };
21
22     $routeProvider.when('/cat/volcopy/:dataKey', {
23         templateUrl: './cat/volcopy/t_view',
24         controller: 'EditCtrl',
25         resolve : resolver
26     });
27
28 })
29
30 .factory('itemSvc', 
31        ['egCore','$q',
32 function(egCore , $q) {
33
34     var service = {
35         tree : {}, // holds lib->cn->copy hash stack
36         copies : [] // raw copy list
37     };
38
39     // returns a promise resolved with the list of circ mods
40     service.get_classifications = function() {
41         if (egCore.env.acnc)
42             return $q.when(egCore.env.acnc.list);
43
44         return egCore.pcrud.retrieveAll('acnc', null, {atomic : true})
45         .then(function(list) {
46             egCore.env.absorbList(list, 'acnc');
47             return list;
48         });
49     };
50
51     service.get_prefixes = function(org) {
52         return egCore.pcrud.search('acnp',
53             {owning_lib : egCore.org.fullPath(org, true)},
54             null, {atomic : true}
55         );
56
57     };
58
59     service.get_statcats = function(orgs) {
60         return egCore.pcrud.search('asc',
61             {owner : orgs},
62             { flesh : 1,
63               flesh_fields : {
64                 asc : ['owner','entries']
65               }
66             },
67             { atomic : true }
68         );
69     };
70
71     service.get_locations = function(orgs) {
72         return egCore.pcrud.search('acpl',
73             {owning_lib : orgs},
74             null, {atomic : true}
75         );
76     };
77
78     service.get_suffixes = function(org) {
79         return egCore.pcrud.search('acns',
80             {owning_lib : egCore.org.fullPath(org, true)},
81             null, {atomic : true}
82         );
83
84     };
85
86     service.get_statuses = function() {
87         if (egCore.env.ccs)
88             return $q.when(egCore.env.ccs.list);
89
90         return egCore.pcrud.retrieveAll('ccs', {}, {atomic : true}).then(
91             function(list) {
92                 egCore.env.absorbList(list, 'ccs');
93                 return list;
94             }
95         );
96
97     };
98
99     service.get_circ_mods = function() {
100         if (egCore.env.ccm)
101             return $q.when(egCore.env.ccm.list);
102
103         return egCore.pcrud.retrieveAll('ccm', {}, {atomic : true}).then(
104             function(list) {
105                 egCore.env.absorbList(list, 'ccm');
106                 return list;
107             }
108         );
109
110     };
111
112     service.get_circ_types = function() {
113         if (egCore.env.citm)
114             return $q.when(egCore.env.citm.list);
115
116         return egCore.pcrud.retrieveAll('citm', {}, {atomic : true}).then(
117             function(list) {
118                 egCore.env.absorbList(list, 'citm');
119                 return list;
120             }
121         );
122
123     };
124
125     service.get_age_protects = function() {
126         if (egCore.env.crahp)
127             return $q.when(egCore.env.crahp.list);
128
129         return egCore.pcrud.retrieveAll('crahp', {}, {atomic : true}).then(
130             function(list) {
131                 egCore.env.absorbList(list, 'crahp');
132                 return list;
133             }
134         );
135
136     };
137
138     service.bmp_parts = {};
139     service.get_parts = function(rec) {
140         if (service.bmp_parts[rec])
141             return $q.when(service.bmp_parts[rec]);
142
143         return egCore.pcrud.search('bmp',
144             {record : rec},
145             null, {atomic : true}
146         ).then(function(list) {
147             service.bmp_parts[rec] = list;
148             return list;
149         });
150
151     };
152
153     service.flesh = {   
154         flesh : 3, 
155         flesh_fields : {
156             acp : ['call_number','parts','stat_cat_entries', 'notes'],
157             acn : ['label_class','prefix','suffix']
158         }
159     }
160
161     service.addCopy = function (cp) {
162
163         if (!cp.parts()) cp.parts([]); // just in case...
164
165         var lib = cp.call_number().owning_lib();
166         var cn = cp.call_number().id();
167
168         if (!service.tree[lib]) service.tree[lib] = {};
169         if (!service.tree[lib][cn]) service.tree[lib][cn] = [];
170
171         service.tree[lib][cn].push(cp);
172         service.copies.push(cp);
173     }
174
175     service.fetchIds = function(idList) {
176         service.tree = {}; // clear the tree on fetch
177         service.copies = []; // clear the copy list on fetch
178         return egCore.pcrud.search('acp', { 'id' : idList }, service.flesh).then(null,null,
179             function(copy) {
180                 service.addCopy(copy);
181             }
182         );
183     }
184
185     return service;
186 }])
187
188 .directive("egVolCopyEdit", function () {
189     return {
190         restrict: 'E',
191         replace: true,
192         template:
193             '<div class="row">'+
194                 '<div class="col-xs-5">'+
195                     '<input id="{{callNumber.id()}}.{{copy.id()}}"'+
196                     ' eg-enter="nextBarcode()" class="form-control"'+
197                     ' type="text" ng-model="barcode" ng-change="updateBarcode()"/>'+
198                 '</div>'+
199                 '<div class="col-xs-3"><input class="form-control" type="number" ng-model="copy_number" ng-change="updateCopyNo()"/></div>'+
200                 '<div class="col-xs-4"><eg-basic-combo-box list="parts" selected="part"></eg-basic-combo-box></div>'+
201             '</div>',
202
203         scope: { copy: "=", callNumber: "=", index: "@" },
204         controller : ['$scope','itemSvc','egCore',
205             function ( $scope , itemSvc , egCore ) {
206                 $scope.new_part_id = 0;
207
208                 $scope.nextBarcode = function (i) {
209                     $scope.$parent.focusNextBarcode($scope.copy.id());
210                 }
211
212                 $scope.updateBarcode = function () { $scope.copy.barcode($scope.barcode); $scope.copy.ischanged(1); };
213                 $scope.updateCopyNo = function () { $scope.copy.copy_number($scope.copy_number); $scope.copy.ischanged(1); };
214                 $scope.updatePart = function () {
215                     if ($scope.part) {
216                         var p = $scope.part_list.filter(function (x) {
217                             return x.label() == $scope.part
218                         });
219                         if (p.length > 0) { // preexisting part
220                             $scope.copy.parts(p)
221                         } else { // create one...
222                             var part = new egCore.idl.bmp();
223                             part.id( --$scope.new_part_id );
224                             part.isnew( true );
225                             part.label( $scope.part );
226                             part.record( $scope.callNumber.owning_lib() );
227                             $scope.copy.parts([part]);
228                             $scope.copy.ischanged(1);
229                         }
230                     } else {
231                         $scope.copy.parts([]);
232                     }
233                 }
234                 $scope.$watch('part', $scope.updatePart);
235
236                 $scope.barcode = $scope.copy.barcode();
237                 $scope.copy_number = $scope.copy.copy_number();
238
239                 if ($scope.copy.parts()) {
240                     $scope.part = $scope.copy.parts()[0];
241                     if ($scope.part) $scope.part = $scope.part.label();
242                 };
243
244                 $scope.parts = [];
245                 $scope.part_list = [];
246
247                 itemSvc.get_parts($scope.callNumber.record()).then(function(list){
248                     $scope.part_list = list;
249                     angular.forEach(list, function(p){ $scope.parts.push(p.label()) });
250                     $scope.parts = angular.copy($scope.parts);
251                 });
252
253             }
254         ]
255
256     }
257 })
258
259 .directive("egVolRow", function () {
260     return {
261         restrict: 'E',
262         replace: true,
263         transclude: true,
264         template:
265             '<div class="row">'+
266                 '<div class="col-xs-2">'+
267                     '<select class="form-control" ng-model="classification" ng-options="cl.name() for cl in classification_list track by idTracker(cl)"/>'+
268                 '</div>'+
269                 '<div class="col-xs-1">'+
270                     '<select class="form-control" ng-model="prefix" ng-change="updatePrefix()" ng-options="p.label() for p in prefix_list track by idTracker(p)"/>'+
271                 '</div>'+
272                 '<div class="col-xs-2"><input class="form-control" type="text" ng-change="updateLabel()" ng-model="label"/></div>'+
273                 '<div class="col-xs-1">'+
274                     '<select class="form-control" ng-model="suffix" ng-change="updateSuffix()" ng-options="s.label() for s in suffix_list track by idTracker(s)"/>'+
275                 '</div>'+
276                 '<div class="col-xs-1"><input class="form-control" type="number" ng-model="copy_count" min="{{orig_copy_count}}" ng-change="changeCPCount()"></div>'+
277                 '<div class="col-xs-5">'+
278                     '<eg-vol-copy-edit ng-repeat="cp in copies track by idTracker(cp)" copy="cp" call-number="callNumber"></eg-vol-copy-edit>'+
279                 '</div>'+
280             '</div>',
281
282         scope: {allcopies: "=", copies: "=" },
283         controller : ['$scope','itemSvc','egCore',
284             function ( $scope , itemSvc , egCore ) {
285                 $scope.new_cp_id = 0;
286                 $scope.callNumber =  $scope.copies[0].call_number();
287
288                 $scope.idTracker = function (x) { if (x) return x.id() };
289
290                 // XXX $() is not working! arg
291                 $scope.focusNextBarcode = function (i) {
292                     var n;
293                     var yep = false;
294                     angular.forEach($scope.copies, function (cp) {
295                         if (n) return;
296
297                         if (cp.id() == i) {
298                             yep = true;
299                             return;
300                         }
301
302                         if (yep) n = cp.id();
303                     });
304
305                     if (n) {
306                         var next = '#' + $scope.callNumber.id() + '.' + n;
307                         var el = $(next).get(0);
308                         if (el) el.focus()
309                     }
310                 }
311
312                 $scope.suffix_list = [];
313                 itemSvc.get_suffixes($scope.callNumber.owning_lib()).then(function(list){
314                     $scope.suffix_list = list;
315                 });
316                 $scope.updateSuffix = function () {
317                     angular.forEach($scope.copies, function(cp) {
318                         cp.call_number().suffix($scope.suffix);
319                         cp.call_number().ischanged(1);
320                     });
321                 }
322
323                 $scope.prefix_list = [];
324                 itemSvc.get_prefixes($scope.callNumber.owning_lib()).then(function(list){
325                     $scope.prefix_list = list;
326                 });
327                 $scope.updatePrefix = function () {
328                     angular.forEach($scope.copies, function(cp) {
329                         cp.call_number().prefix($scope.prefix);
330                         cp.call_number().ischanged(1);
331                     });
332                 }
333
334                 $scope.classification_list = [];
335                 itemSvc.get_classifications().then(function(list){
336                     $scope.classification_list = list;
337                 });
338                 $scope.updateClassification = function () {
339                     angular.forEach($scope.copies, function(cp) {
340                         cp.call_number().label_class($scope.classification);
341                         cp.call_number().ischanged(1);
342                     });
343                 }
344
345                 $scope.updateLabel = function () {
346                     angular.forEach($scope.copies, function(cp) {
347                         cp.call_number().label($scope.label);
348                         cp.call_number().ischanged(1);
349                     });
350                 }
351
352                 $scope.$watch('callNumber.prefix()', function (v) {
353                     if (typeof v != 'object') {
354                         $scope.prefix = $scope.prefix_list.filter(function (p) {
355                             return p.id() == v;
356                         })[0];
357                         $scope.callNumber.prefix($scope.prefix);
358                     }
359                 });
360
361                 $scope.$watch('callNumber.suffix()', function (v) {
362                     if (typeof v != 'object') {
363                         $scope.suffix = $scope.suffix_list.filter( function (s) {
364                             return s.id() == v;
365                         })[0];
366                         $scope.callNumber.suffix($scope.suffix);
367                     }
368                 });
369
370                 $scope.$watch('callNumber.label_class()', function (v) {
371                     if (typeof v != 'object') {
372                         $scope.classification = $scope.classification_list.filter(function (c) {
373                             return c.id() == v;
374                         })[0];
375                         $scope.callNumber.label_class($scope.classification);
376                     }
377                 });
378
379                 $scope.$watch('callNumber.label()', function (v) {
380                     $scope.label = v;
381                 });
382
383                 $scope.prefix = $scope.callNumber.prefix();
384                 $scope.suffix = $scope.callNumber.suffix();
385                 $scope.classification = $scope.callNumber.label_class();
386                 $scope.label = $scope.callNumber.label();
387
388                 $scope.copy_count = $scope.copies.length;
389                 $scope.orig_copy_count = $scope.copy_count;
390
391                 $scope.changeCPCount = function () {
392                     while ($scope.copy_count > $scope.copies.length) {
393                         var cp = new egCore.idl.acp();
394                         cp.id( --$scope.new_cp_id );
395                         cp.isnew( true );
396                         cp.circ_lib( $scope.lib );
397                         cp.call_number( $scope.callNumber );
398                         $scope.copies.push( cp );
399                         $scope.allcopies.push( cp );
400                     }
401
402                     if ($scope.copy_count >= $scope.orig_copy_count) {
403                         var how_many = $scope.copies.length - $scope.copy_count;
404                         if (how_many > 0) {
405                             var dead = $scope.copies.splice($scope.copy_count,how_many);
406                             $scope.callNumber.copies($scope.copies);
407
408                             // Trimming the global list is a bit more tricky
409                             angular.forEach( dead, function (d) {
410                                 angular.forEach( $scope.allcopies, function (l, i) { 
411                                     if (l === d) $scope.allcopies.splice(i,1);
412                                 });
413                             });
414                         }
415                     }
416                 }
417
418             }
419         ]
420
421     }
422 })
423
424 .directive("egVolEdit", function () {
425     return {
426         restrict: 'E',
427         replace: true,
428         template:
429             '<div class="row">'+
430                 '<div class="col-xs-1"><eg-org-selector selected="owning_lib" disableTest="cant_have_vols"></eg-org-selector></div>'+
431                 '<div class="col-xs-1"><input class="form-control" type="number" min="{{orig_cn_count}}" ng-model="cn_count" ng-change="changeCNCount()"/></div>'+
432                 '<div class="col-xs-10">'+
433                     '<eg-vol-row ng-repeat="(cn,copies) in struct track by cn" copies="copies" allcopies="allcopies"></eg-vol-row>'+
434                 '</div>'+
435             '</div>',
436
437         scope: { allcopies: "=", struct: "=", lib: "@", record: "@" },
438         controller : ['$scope','itemSvc','egCore',
439             function ( $scope , itemSvc , egCore ) {
440                 $scope.new_cn_id = 0;
441                 $scope.first_cn = Object.keys($scope.struct)[0];
442                 $scope.full_cn = $scope.struct[$scope.first_cn][0].call_number();
443
444                 $scope.cn_count = Object.keys($scope.struct).length;
445                 $scope.orig_cn_count = $scope.cn_count;
446
447                 $scope.owning_lib = egCore.org.get($scope.lib);
448                 $scope.$watch('owning_lib', function (l) {
449                     angular.forEach( $scope.struct[$scope.first_cn], function (cp) {
450                         cp.call_number().owning_lib( $scope.owning_lib.id() );
451                     });
452                 });
453
454                 $scope.cant_have_vols = function (id) { return !egCore.org.CanHaveVolumes(id); };
455
456                 $scope.$watch('cn_count', function (n) {
457                     var o = Object.keys($scope.struct).length;
458                     if (n > o) { // adding
459                         for (var i = o; o < n; o++) {
460                             var cn = new egCore.idl.acn();
461                             cn.id( --$scope.new_cn_id );
462                             cn.isnew( true );
463                             cn.owning_lib( $scope.owning_lib.id() );
464                             cn.record( $scope.full_cn.record() );
465
466                             var cp = new egCore.idl.acp();
467                             cp.id( --$scope.new_cp_id );
468                             cp.isnew( true );
469                             cp.circ_lib( $scope.owning_lib.id() );
470                             cp.call_number( cn );
471
472                             $scope.struct[cn.id()] = [cp];
473                             $scope.allcopies.push(cp);
474                         }
475                     } else if (n < o && n >= $scope.orig_cn_count) { // removing
476                         var how_many = o - n;
477                         var list = Object
478                                 .keys($scope.struct)
479                                 .sort(function(a, b){return a-b})
480                                 .reverse();
481                         for (var i = how_many; i > 0; i--) {
482                             // Trimming the global list is a bit more tricky
483                             angular.forEach($scope.struct[list[i]], function (d) {
484                                 angular.forEach( $scope.allcopies, function (l, j) { 
485                                     if (l === d) $scope.allcopies.splice(j,1);
486                                 });
487                             });
488                             delete $scope.struct[list[i]];
489                         }
490                     }
491                 });
492             }
493         ]
494
495     }
496 })
497
498 /**
499  * Edit controller!
500  */
501 .controller('EditCtrl', 
502        ['$scope','$q','$window','$routeParams','$location','$timeout','egCore','egNet','egGridDataProvider','itemSvc','$modal',
503 function($scope , $q , $window , $routeParams , $location , $timeout , egCore , egNet , egGridDataProvider , itemSvc , $modal) {
504
505     $scope.defaults = { // If defaults are not set at all, allow everything
506         statcats : true,
507         copy_notes : true,
508         attributes : {
509             status : true,
510             loan_duration : true,
511             fine_level : true,
512             cost : true,
513             alerts : true,
514             deposit : true,
515             deposit_amount : true,
516             opac_visible : true,
517             price : true,
518             circulate : true,
519             mint_condition : true,
520             circ_lib : true,
521             ref : true,
522             circ_modifier : true,
523             circ_as_type : true,
524             location : true,
525             holdable : true,
526             age_protect : true
527         }
528     };
529
530     $scope.saveDefaults = function () {
531         egCore.hatch.setItem('cat.copy.defaults', $scope.defaults);
532     }
533
534     $scope.fetchDefaults = function () {
535         egCore.hatch.getItem('cat.copy.defaults').then(function(t) {
536             if (t) {
537                 $scope.defaults = t;
538                 if (!$scope.batch) $scope.batch = {};
539                 $scope.batch.classification = $scope.defaults.classification;
540                 $scope.batch.prefix = $scope.defaults.prefix;
541                 $scope.batch.suffix = $scope.defaults.suffix;
542                 $scope.working.statcat_filter = $scope.defaults.statcat_filter;
543                 if ($scope.defaults.always_vols) $scope.show_vols = true;
544             }
545         });
546     }
547     $scope.fetchDefaults();
548
549     $scope.dirty = false;
550     $scope.$watch('dirty',
551         function(newVal, oldVal) {
552             if (newVal && newVal != oldVal) {
553                 $($window).on('beforeunload.edit', function(){
554                     return 'There is unsaved data!'
555                 });
556             } else {
557                 $($window).off('beforeunload.edit');
558             }
559         }
560     );
561
562     $scope.show_vols = true;
563     $scope.show_copies = true;
564
565     $scope.tracker = function (x,f) { if (x) return x[f]() };
566     $scope.idTracker = function (x) { if (x) return $scope.tracker(x,'id') };
567     $scope.cant_have_vols = function (id) { return !egCore.org.CanHaveVolumes(id); };
568
569     $scope.orgById = function (id) { return egCore.org.get(id) }
570     $scope.statusById = function (id) {
571         return $scope.status_list.filter( function (s) { return s.id() == id } )[0];
572     }
573     $scope.locationById = function (id) {
574         return $scope.location_cache[''+id];
575     }
576
577     $scope.workingToComplete = function () {
578         angular.forEach( $scope.workingGridControls.selectedItems(), function (c) {
579             angular.forEach( itemSvc.copies, function (w, i) {
580                 if (c === w)
581                     $scope.completed_copies = $scope.completed_copies.concat(itemSvc.copies.splice(i,1));
582             });
583         });
584     }
585
586     $scope.completeToWorking = function () {
587         angular.forEach( $scope.completedGridControls.selectedItems(), function (c) {
588             angular.forEach( $scope.completed_copies, function (w, i) {
589                 if (c === w)
590                     itemSvc.copies = itemSvc.copies.concat($scope.completed_copies.splice(i,1));
591             });
592         });
593     }
594
595     createSimpleUpdateWatcher = function (field) {
596         return $scope.$watch('working.' + field, function () {
597             var newval = $scope.working[field];
598
599             if (typeof newval != 'undefined') {
600                 if (angular.isObject(newval)) { // we'll use the pkey
601                     if (newval.id) newval = newval.id();
602                     else if (newval.code) newval = newval.code();
603                 }
604
605                 if (""+newval == "" || newval == null) {
606                     $scope.working[field] = undefined;
607                     newval = null;
608                 }
609
610                 if ($scope.workingGridControls && $scope.workingGridControls.selectedItems) {
611                     angular.forEach(
612                         $scope.workingGridControls.selectedItems(),
613                         function (cp) {
614                             if (cp[field]() !== newval) {
615                                 cp[field](newval);
616                                 cp.ischanged(1);
617                                 $scope.dirty = true;
618                             }
619                         }
620                     );
621                 }
622             }
623         });
624     }
625
626     $scope.working = {
627         statcats: {},
628         statcat_filter: undefined
629     };
630
631     $scope.statcatUpdate = function (id) {
632         var newval = $scope.working.statcats[id];
633
634         if (typeof newval != 'undefined') {
635             if (angular.isObject(newval)) { // we'll use the pkey
636                 newval = newval.id();
637             }
638     
639             if (""+newval == "" || newval == null) {
640                 $scope.working.statcats[id] = undefined;
641                 newval = null;
642             }
643     
644             if (!$scope.in_item_select && $scope.workingGridControls && $scope.workingGridControls.selectedItems) {
645                 angular.forEach(
646                     $scope.workingGridControls.selectedItems(),
647                     function (cp) {
648                         $scope.dirty = true;
649
650                         cp.stat_cat_entries(
651                             angular.forEach( cp.stat_cat_entries(), function (e) {
652                                 if (e.stat_cat() == id) { // mark deleted
653                                     e.isdeleted(1);
654                                 }
655                             })
656                         );
657     
658                         if (newval) {
659                             var e = new egCore.idl.ascecm();
660                             e.isnew( 1 );
661                             e.owning_copy( cp.id() );
662                             e.stat_cat( id );
663                             e.stat_cat_entry( newval );
664
665                             cp.stat_cat_entries(
666                                 cp.stat_cat_entries().concat([ e ])
667                             );
668
669                         }
670
671                         cp.stat_cat_entries( // trim out ephemeral deleted ones
672                             cp.stat_cat_entries().filter(function (e) {
673                                 if (Boolean(e.isnew())) {
674                                     if (Boolean(e.isdeleted())) {
675                                         return false;
676                                     }
677                                 }
678                                 return true;
679                             })
680                         );
681    
682                         cp.ischanged(1);
683                     }
684                 );
685             }
686         }
687     }
688
689     var dataKey = $routeParams.dataKey;
690     console.debug('dataKey: ' + dataKey);
691
692     if (dataKey && dataKey.length > 0) {
693
694         $scope.templates = {};
695         $scope.template_name = '';
696         $scope.template_name_list = [];
697
698         $scope.fetchTemplates = function () {
699             egCore.hatch.getItem('cat.copy.templates').then(function(t) {
700                 if (t) {
701                     $scope.templates = t;
702                     $scope.template_name_list = Object.keys(t);
703                 }
704             });
705         }
706         $scope.fetchTemplates();
707
708          $scope.applyTemplate = function (n) {
709             angular.forEach($scope.templates[n], function (v,k) {
710                 if (!angular.isObject(v)) {
711                     $scope.working[k] = angular.copy(v);
712                 } else {
713                     angular.forEach(v, function (sv,sk) {
714                         if (k == 'callnumber') {
715                             angular.forEach(v, function (cnv,cnk) {
716                                 $scope.batch[cnk] = cnv;
717                             });
718                             $scope.applyBatchCNValues();
719                         } else {
720                             $scope.working[k][sk] = angular.copy(sv);
721                             if (k == 'statcats') $scope.statcatUpdate(sk);
722                         }
723                     });
724                 }
725             });
726             $scope.template_name = '';
727         }
728
729         $scope.copytab = 'working';
730         $scope.tab = 'edit';
731         $scope.summaryRecord = null;
732         $scope.record_id = null;
733         $scope.data = {};
734         $scope.completed_copies = [];
735         $scope.location_orgs = [];
736         $scope.location_cache = {};
737         $scope.statcats = [];
738         if (!$scope.batch) $scope.batch = {};
739
740         $scope.applyBatchCNValues = function () {
741             if ($scope.data.tree) {
742                 angular.forEach($scope.data.tree, function(cn_hash) {
743                     angular.forEach(cn_hash, function(copies) {
744                         angular.forEach(copies, function(cp) {
745                             if (typeof $scope.batch.classification != 'undefined' && $scope.batch.classification != '')
746                                 cp.call_number().label_class($scope.batch.classification);
747                                 $scope.dirty = true;
748                             if (typeof $scope.batch.prefix != 'undefined' && $scope.batch.prefix != '')
749                                 cp.call_number().prefix($scope.batch.prefix);
750                                 $scope.dirty = true;
751                             if (typeof $scope.batch.label != 'undefined' && $scope.batch.label != '')
752                                 cp.call_number().label($scope.batch.label);
753                                 $scope.dirty = true;
754                             if (typeof $scope.batch.suffix != 'undefined' && $scope.batch.suffix != '')
755                                 cp.call_number().suffix($scope.batch.suffix);
756                                 $scope.dirty = true;
757                         });
758                     });
759                 });
760             }
761         }
762
763         $scope.clearWorking = function () {
764             angular.forEach($scope.working, function (v,k,o) {
765                 if (!angular.isObject(v)) {
766                     if (typeof v != 'undefined')
767                         $scope.working[k] = undefined;
768                 } else if (k != 'circ_lib') {
769                     angular.forEach(v, function (sv,sk) {
770                         if (typeof v != 'undefined')
771                             $scope.working[k][sk] = undefined;
772                     });
773                 }
774             });
775             $scope.working.circ_lib = undefined; // special
776         }
777
778         $scope.completedGridDataProvider = egGridDataProvider.instance({
779             get : function(offset, count) {
780                 //return provider.arrayNotifier(itemSvc.copies, offset, count);
781                 return this.arrayNotifier($scope.completed_copies, offset, count);
782             }
783         });
784
785         $scope.completedGridControls = {};
786
787         $scope.workingGridDataProvider = egGridDataProvider.instance({
788             get : function(offset, count) {
789                 //return provider.arrayNotifier(itemSvc.copies, offset, count);
790                 return this.arrayNotifier(itemSvc.copies, offset, count);
791             }
792         });
793
794         $scope.workingGridControls = {};
795
796         egNet.request(
797             'open-ils.actor',
798             'open-ils.actor.anon_cache.get_value',
799             dataKey, 'edit-these-copies'
800         ).then(function (data) {
801
802             if (data) {
803                 if (data.hide_vols && !$scope.defaults.always_vols) $scope.show_vols = false;
804                 if (data.hide_copies) $scope.show_copies = false;
805
806                 $scope.record_id = data.record_id;
807
808                 if (data.copies && data.copies.length)
809                     return itemSvc.fetchIds(data.copies);
810
811                 if (data.raw && data.raw.length) {
812
813                     /* data.raw must be an array of copies with (at least)
814                      * the call number fleshed on each.  For new copies
815                      * create from whole cloth, the id for each should
816                      * probably be negative and isnew() should return true.
817                      * Each /distinct/ call number must have a distinct id
818                      * as well, probably negative also if they're new. Clear?
819                      */
820
821                     angular.forEach(
822                         data.raw,
823                         function (cp) { itemSvc.addCopy(cp) }
824                     );
825
826                     return itemSvc.copies;
827                 }
828             }
829
830         }).then( function() {
831             $scope.data = itemSvc;
832             $scope.workingGridDataProvider.refresh();
833         });
834
835         $scope.in_item_select = false;
836         $scope.afterItemSelect = function() { $scope.in_item_select = false };
837         $scope.handleItemSelect = function (item_list) {
838             if (item_list && item_list.length > 0) {
839                 $scope.in_item_select = true;
840
841                 angular.forEach(Object.keys($scope.defaults.attributes), function (attr) {
842
843                     var value_hash = {};
844                     angular.forEach(item_list, function (item) {
845                         if (item[attr]) {
846                             var v = item[attr]()
847                             if (angular.isObject(v)) {
848                                 if (v.id) v = v.id();
849                                 else if (v.code) v = v.code();
850                             }
851                             value_hash[v] = 1;
852                         }
853                     });
854
855                     if (Object.keys(value_hash).length == 1) {
856                         if (attr == 'circ_lib') {
857                             $scope.working[attr] = egCore.org.get(item_list[0][attr]());
858                         } else {
859                             $scope.working[attr] = item_list[0][attr]();
860                         }
861                     } else {
862                         $scope.working[attr] = undefined;
863                     }
864                 });
865
866                 angular.forEach($scope.statcats, function (sc) {
867
868                     var counter = -1;
869                     var value_hash = {};
870                     var none = false;
871                     angular.forEach(item_list, function (item) {
872                         if (item.stat_cat_entries()) {
873                             if (item.stat_cat_entries().length > 0) {
874                                 var right_sc = item.stat_cat_entries().filter(function (e) {
875                                     return e.stat_cat() == sc.id() && !Boolean(e.isdeleted());
876                                 });
877
878                                 if (right_sc.length > 0) {
879                                     value_hash[right_sc[0].stat_cat_entry()] = right_sc[0].stat_cat_entry();
880                                 } else {
881                                     none = true;
882                                 }
883                             }
884                         } else {
885                             none = true;
886                         }
887                     });
888
889                     if (!none && Object.keys(value_hash).length == 1) {
890                         $scope.working.statcats[sc.id()] = value_hash[Object.keys(value_hash)[0]];
891                     } else {
892                         $scope.working.statcats[sc.id()] = undefined;
893                     }
894                 });
895
896             } else {
897                 $scope.clearWorking();
898             }
899
900         }
901
902         $scope.$watch('data.copies.length', function () {
903             if ($scope.data.copies) {
904                 var base_orgs = $scope.data.copies.map(function(cp){
905                     return cp.circ_lib()
906                 }).concat(
907                     $scope.data.copies.map(function(cp){
908                         return cp.call_number().owning_lib()
909                     })
910                 ).concat(
911                     [egCore.auth.user().ws_ou()]
912                 ).filter(function(e,i,a){
913                     return a.lastIndexOf(e) === i;
914                 });
915
916                 var all_orgs = [];
917                 angular.forEach(base_orgs, function(o) {
918                     all_orgs = all_orgs.concat( egCore.org.fullPath(o, true) );
919                 });
920
921                 var final_orgs = all_orgs.filter(function(e,i,a){
922                     return a.lastIndexOf(e) === i;
923                 }).sort(function(a,b){return b-a});
924
925                 if ($scope.location_orgs.toString() != final_orgs.toString()) {
926                     $scope.location_orgs = final_orgs;
927                     if ($scope.location_orgs.length) {
928                         itemSvc.get_locations($scope.location_orgs).then(function(list){
929                             angular.forEach(list, function(l) {
930                                 $scope.location_cache[ ''+l.id() ] = l;
931                             });
932                             $scope.location_list = list;
933                         });
934
935                         $scope.statcat_filter_list = [];
936                         angular.forEach($scope.location_orgs, function (o) {
937                             $scope.statcat_filter_list.push(egCore.org.get(o));
938                         });
939
940                         itemSvc.get_statcats($scope.location_orgs).then(function(list){
941                             $scope.statcats = list;
942                             angular.forEach($scope.statcats, function (s) {
943
944                                 if (!$scope.working)
945                                     $scope.working = { statcats: {}, statcat_filter: undefined};
946                                 if (!$scope.working.statcats)
947                                     $scope.working.statcats = {};
948
949                                 if (!$scope.in_item_select) {
950                                     $scope.working.statcats[s.id()] = undefined;
951                                 }
952                                 createStatcatUpdateWatcher(s.id());
953                             });
954                             $scope.in_item_select = false;
955                         });
956                     }
957                 }
958             }
959
960             $scope.workingGridDataProvider.refresh();
961         });
962
963         $scope.suffix_list = [];
964         itemSvc.get_suffixes(egCore.auth.user().ws_ou()).then(function(list){
965             $scope.suffix_list = list;
966         });
967
968         $scope.prefix_list = [];
969         itemSvc.get_prefixes(egCore.auth.user().ws_ou()).then(function(list){
970             $scope.prefix_list = list;
971         });
972
973         $scope.classification_list = [];
974         itemSvc.get_classifications().then(function(list){
975             $scope.classification_list = list;
976         });
977
978         $scope.$watch('completed_copies.length', function () {
979             $scope.completedGridDataProvider.refresh();
980         });
981
982         $scope.location_list = [];
983         itemSvc.get_locations().then(function(list){
984             $scope.location_list = list;
985         });
986         createSimpleUpdateWatcher('location');
987
988         $scope.status_list = [];
989         itemSvc.get_statuses().then(function(list){
990             $scope.status_list = list;
991         });
992         createSimpleUpdateWatcher('status');
993
994         $scope.circ_modifier_list = [];
995         itemSvc.get_circ_mods().then(function(list){
996             $scope.circ_modifier_list = list;
997         });
998         createSimpleUpdateWatcher('circ_modifier');
999
1000         $scope.circ_type_list = [];
1001         itemSvc.get_circ_types().then(function(list){
1002             $scope.circ_type_list = list;
1003         });
1004         createSimpleUpdateWatcher('circ_as_type');
1005
1006         $scope.age_protect_list = [];
1007         itemSvc.get_age_protects().then(function(list){
1008             $scope.age_protect_list = list;
1009         });
1010         createSimpleUpdateWatcher('age_protect');
1011
1012         createSimpleUpdateWatcher('circ_lib');
1013         createSimpleUpdateWatcher('circulate');
1014         createSimpleUpdateWatcher('holdable');
1015         createSimpleUpdateWatcher('fine_level');
1016         createSimpleUpdateWatcher('loan_duration');
1017         createSimpleUpdateWatcher('cost');
1018         createSimpleUpdateWatcher('deposit');
1019         createSimpleUpdateWatcher('deposit_amount');
1020         createSimpleUpdateWatcher('mint_condition');
1021         createSimpleUpdateWatcher('opac_visible');
1022         createSimpleUpdateWatcher('ref');
1023
1024         $scope.saveCompletedCopies = function (and_exit) {
1025             var cnHash = {};
1026             var perCnCopies = {};
1027             angular.forEach( $scope.completed_copies, function (cp) {
1028                 var cn_id = cp.call_number().id();
1029                 if (!cnHash[cn_id]) {
1030                     cnHash[cn_id] = cp.call_number();
1031                     perCnCopies[cn_id] = [cp];
1032                 } else {
1033                     perCnCopies[cn_id].push(cp);
1034                 }
1035                 cp.call_number(cn_id); // prevent loops in JSON-ification
1036             });
1037
1038             angular.forEach(perCnCopies, function (v, k) {
1039                 cnHash[k].copies(v);
1040             });
1041
1042             cnList = [];
1043             angular.forEach(cnHash, function (v, k) {
1044                 cnList.push(v);
1045             });
1046
1047             egNet.request(
1048                 'open-ils.cat',
1049                 'open-ils.cat.asset.volume.fleshed.batch.update.override',
1050                 egCore.auth.token(), cnList, 1, { auto_merge_vols : 1, create_parts : 1 }
1051             ).then(function(update_count) {
1052                 if (and_exit) {
1053                     $scope.dirty = false;
1054                     $timeout(function(){$window.close()});
1055                 }
1056             });
1057         }
1058
1059         $scope.saveAndExit = function () {
1060             $scope.saveCompletedCopies(true);
1061         }
1062
1063     }
1064
1065     $scope.copy_notes_dialog = function(copy_list) {
1066         var default_pub = Boolean($scope.defaults.copy_notes_pub);
1067         if (!angular.isArray(copy_list)) copy_list = [copy_list];
1068
1069         return $modal.open({
1070             templateUrl: './cat/volcopy/t_copy_notes',
1071             animation: true,
1072             controller:
1073                    ['$scope','$modalInstance',
1074             function($scope , $modalInstance) {
1075                 $scope.focusNote = true;
1076                 $scope.note = {
1077                     creator : egCore.auth.user().id(),
1078                     title   : '',
1079                     value   : '',
1080                     pub     : default_pub,
1081                 };
1082
1083                 $scope.require_initials = false;
1084                 egCore.org.settings([
1085                     'ui.staff.require_initials.copy_notes'
1086                 ]).then(function(set) {
1087                     $scope.require_initials = Boolean(set['ui.staff.require_initials.copy_notes']);
1088                 });
1089
1090                 $scope.note_list = [];
1091                 if (copy_list.length == 1) {
1092                     $scope.note_list = copy_list[0].notes();
1093                 }
1094
1095                 $scope.ok = function(note) {
1096
1097                     if (note.initials) note.value += ' [' + note.initials + ']';
1098                     angular.forEach(copy_list, function (cp) {
1099                         var n = new egCore.idl.acpn();
1100                         n.creator(note.creator);
1101                         n.pub(note.pub);
1102                         n.title(note.title);
1103                         n.value(note.value);
1104                         n.owning_copy(cp.id());
1105                         cp.notes().push( n );
1106                     });
1107
1108                     $modalInstance.close();
1109                 }
1110
1111                 $scope.cancel = function($event) {
1112                     $modalInstance.dismiss();
1113                     $event.preventDefault();
1114                 }
1115             }]
1116         });
1117     }
1118
1119 }])
1120
1121 .directive("egVolTemplate", function () {
1122     return {
1123         restrict: 'E',
1124         replace: true,
1125         template: '<div ng-include="'+"'/eg/staff/cat/volcopy/t_attr_edit'"+'"></div>',
1126         scope: { },
1127         controller : ['$scope','$window','itemSvc','egCore',
1128             function ( $scope , $window , itemSvc , egCore ) {
1129
1130                 $scope.defaults = { // If defaults are not set at all, allow everything
1131                     statcats : true,
1132                     copy_notes : true,
1133                     attributes : {
1134                         status : true,
1135                         loan_duration : true,
1136                         fine_level : true,
1137                         cost : true,
1138                         alerts : true,
1139                         deposit : true,
1140                         deposit_amount : true,
1141                         opac_visible : true,
1142                         price : true,
1143                         circulate : true,
1144                         mint_condition : true,
1145                         circ_lib : true,
1146                         ref : true,
1147                         circ_modifier : true,
1148                         circ_as_type : true,
1149                         location : true,
1150                         holdable : true,
1151                         age_protect : true
1152                     }
1153                 };
1154
1155                 $scope.fetchDefaults = function () {
1156                     egCore.hatch.getItem('cat.copy.defaults').then(function(t) {
1157                         if (t) {
1158                             $scope.defaults = t;
1159                             $scope.working.statcat_filter = $scope.defaults.statcat_filter;
1160                         }
1161                     });
1162                 }
1163                 $scope.fetchDefaults();
1164
1165                 $scope.dirty = false;
1166                 $scope.$watch('dirty',
1167                     function(newVal, oldVal) {
1168                         if (newVal && newVal != oldVal) {
1169                             $($window).on('beforeunload.template', function(){
1170                                 return 'There is unsaved template data!'
1171                             });
1172                         } else {
1173                             $($window).off('beforeunload.template');
1174                         }
1175                     }
1176                 );
1177
1178                 $scope.template_controls = true;
1179
1180                 $scope.fetchTemplates = function () {
1181                     egCore.hatch.getItem('cat.copy.templates').then(function(t) {
1182                         if (t) {
1183                             $scope.templates = t;
1184                             $scope.template_name_list = Object.keys(t);
1185                         }
1186                     });
1187                 }
1188                 $scope.fetchTemplates();
1189             
1190                 $scope.applyTemplate = function (n) {
1191                     angular.forEach($scope.templates[n], function (v,k) {
1192                         if (!angular.isObject(v)) {
1193                             $scope.working[k] = angular.copy(v);
1194                         } else {
1195                             angular.forEach(v, function (sv,sk) {
1196                                 $scope.working[k][sk] = angular.copy(sv);
1197                             });
1198                         }
1199                     });
1200                     $scope.template_name = '';
1201                 }
1202
1203                 $scope.deleteTemplate = function (n) {
1204                     if (n) {
1205                         delete $scope.templates[n]
1206                         $scope.template_name_list = Object.keys($scope.templates);
1207                         $scope.template_name = '';
1208                         egCore.hatch.setItem('cat.copy.templates', $scope.templates);
1209                         $scope.$parent.fetchTemplates();
1210                     }
1211                 }
1212
1213                 $scope.saveTemplate = function (n) {
1214                     if (n) {
1215                         var tmpl = {};
1216             
1217                         angular.forEach($scope.working, function (v,k) {
1218                             if (angular.isObject(v)) { // we'll use the pkey
1219                                 if (v.id) v = v.id();
1220                                 else if (v.code) v = v.code();
1221                             }
1222             
1223                             tmpl[k] = v;
1224                         });
1225             
1226                         $scope.templates[n] = tmpl;
1227                         $scope.template_name_list = Object.keys($scope.templates);
1228             
1229                         egCore.hatch.setItem('cat.copy.templates', $scope.templates);
1230                         $scope.$parent.fetchTemplates();
1231
1232                         $scope.dirty = false;
1233                     }
1234                 }
1235             
1236                 $scope.templates = {};
1237                 $scope.template_name = '';
1238                 $scope.template_name_list = [];
1239             
1240                 $scope.tracker = function (x,f) { if (x) return x[f]() };
1241                 $scope.idTracker = function (x) { if (x) return $scope.tracker(x,'id') };
1242                 $scope.cant_have_vols = function (id) { return !egCore.org.CanHaveVolumes(id); };
1243             
1244                 $scope.orgById = function (id) { return egCore.org.get(id) }
1245                 $scope.statusById = function (id) {
1246                     return $scope.status_list.filter( function (s) { return s.id() == id } )[0];
1247                 }
1248                 $scope.locationById = function (id) {
1249                     return $scope.location_cache[''+id];
1250                 }
1251             
1252                 createSimpleUpdateWatcher = function (field) {
1253                     $scope.$watch('working.' + field, function () {
1254                         var newval = $scope.working[field];
1255             
1256                         if (typeof newval != 'undefined') {
1257                             $scope.dirty = true;
1258                             if (angular.isObject(newval)) { // we'll use the pkey
1259                                 if (newval.id) $scope.working[field] = newval.id();
1260                                 else if (newval.code) $scope.working[field] = newval.code();
1261                             }
1262             
1263                             if (""+newval == "" || newval == null) {
1264                                 $scope.working[field] = undefined;
1265                             }
1266             
1267                         }
1268                     });
1269                 }
1270             
1271                 $scope.working = {
1272                     statcats: {},
1273                     statcat_filter: undefined
1274                 };
1275             
1276                 createStatcatUpdateWatcher = function (id) {
1277                     return $scope.$watch('working.statcats[' + id + ']', function () {
1278                         if ($scope.working.statcats) {
1279                             var newval = $scope.working.statcats[id];
1280                 
1281                             if (typeof newval != 'undefined') {
1282                                 $scope.dirty = true;
1283                                 if (angular.isObject(newval)) { // we'll use the pkey
1284                                     newval = newval.id();
1285                                 }
1286                 
1287                                 if (""+newval == "" || newval == null) {
1288                                     $scope.working.statcats[id] = undefined;
1289                                     newval = null;
1290                                 }
1291                 
1292                             }
1293                         }
1294                     });
1295                 }
1296
1297                 $scope.clearWorking = function () {
1298                     angular.forEach($scope.working, function (v,k,o) {
1299                         if (!angular.isObject(v)) {
1300                             if (typeof v != 'undefined')
1301                                 $scope.working[k] = undefined;
1302                         } else if (k != 'circ_lib') {
1303                             angular.forEach(v, function (sv,sk) {
1304                                 $scope.working[k][sk] = undefined;
1305                             });
1306                         }
1307                     });
1308                     $scope.working.circ_lib = undefined; // special
1309                     $scope.dirty = false;
1310                 }
1311
1312                 $scope.working = {};
1313                 $scope.location_orgs = [];
1314                 $scope.location_cache = {};
1315             
1316                 $scope.location_list = [];
1317                 itemSvc.get_locations(
1318                     egCore.org.fullPath( egCore.auth.user().ws_ou(), true )
1319                 ).then(function(list){
1320                     $scope.location_list = list;
1321                 });
1322                 createSimpleUpdateWatcher('location');
1323
1324                 $scope.statcat_filter_list = egCore.org.fullPath( egCore.auth.user().ws_ou() );
1325
1326                 $scope.statcats = [];
1327                 itemSvc.get_statcats(
1328                     egCore.org.fullPath( egCore.auth.user().ws_ou(), true )
1329                 ).then(function(list){
1330                     $scope.statcats = list;
1331                     angular.forEach($scope.statcats, function (s) {
1332
1333                         if (!$scope.working)
1334                             $scope.working = { statcats: {}, statcat_filter: undefined};
1335                         if (!$scope.working.statcats)
1336                             $scope.working.statcats = {};
1337
1338                         $scope.working.statcats[s.id()] = undefined;
1339                         createStatcatUpdateWatcher(s.id());
1340                     });
1341                 });
1342             
1343                 $scope.status_list = [];
1344                 itemSvc.get_statuses().then(function(list){
1345                     $scope.status_list = list;
1346                 });
1347                 createSimpleUpdateWatcher('status');
1348             
1349                 $scope.circ_modifier_list = [];
1350                 itemSvc.get_circ_mods().then(function(list){
1351                     $scope.circ_modifier_list = list;
1352                 });
1353                 createSimpleUpdateWatcher('circ_modifier');
1354             
1355                 $scope.circ_type_list = [];
1356                 itemSvc.get_circ_types().then(function(list){
1357                     $scope.circ_type_list = list;
1358                 });
1359                 createSimpleUpdateWatcher('circ_as_type');
1360             
1361                 $scope.age_protect_list = [];
1362                 itemSvc.get_age_protects().then(function(list){
1363                     $scope.age_protect_list = list;
1364                 });
1365                 createSimpleUpdateWatcher('age_protect');
1366             
1367                 createSimpleUpdateWatcher('circ_lib');
1368                 createSimpleUpdateWatcher('circulate');
1369                 createSimpleUpdateWatcher('holdable');
1370                 createSimpleUpdateWatcher('fine_level');
1371                 createSimpleUpdateWatcher('loan_duration');
1372                 createSimpleUpdateWatcher('cost');
1373                 createSimpleUpdateWatcher('deposit');
1374                 createSimpleUpdateWatcher('deposit_amount');
1375                 createSimpleUpdateWatcher('mint_condition');
1376                 createSimpleUpdateWatcher('opac_visible');
1377                 createSimpleUpdateWatcher('ref');
1378
1379                 $scope.suffix_list = [];
1380                 itemSvc.get_suffixes(egCore.auth.user().ws_ou()).then(function(list){
1381                     $scope.suffix_list = list;
1382                 });
1383
1384                 $scope.prefix_list = [];
1385                 itemSvc.get_prefixes(egCore.auth.user().ws_ou()).then(function(list){
1386                     $scope.prefix_list = list;
1387                 });
1388
1389                 $scope.classification_list = [];
1390                 itemSvc.get_classifications().then(function(list){
1391                     $scope.classification_list = list;
1392                 });
1393
1394                 createSimpleUpdateWatcher('working.callnumber.classification');
1395                 createSimpleUpdateWatcher('working.callnumber.prefix');
1396                 createSimpleUpdateWatcher('working.callnumber.suffix');
1397             }
1398         ]
1399     }
1400 })
1401
1402