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