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