]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/cat/volcopy/app.js
LP#1734963: Teach copy template converter about older templates.
[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(['ngToastProvider', function(ngToastProvider) {
15   ngToastProvider.configure({
16     verticalPosition: 'bottom',
17     animation: 'fade'
18   });
19 }])
20
21 .config(function($routeProvider, $locationProvider, $compileProvider) {
22     $locationProvider.html5Mode(true);
23     $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|mailto|blob):/); // grid export
24         
25     var resolver = {
26         delay : ['egStartup', function(egStartup) { return egStartup.go(); }]
27     };
28
29     $routeProvider.when('/cat/volcopy/edit_templates', {
30         templateUrl: './cat/volcopy/t_view',
31         controller: 'EditCtrl',
32         resolve : resolver
33     });
34
35     $routeProvider.when('/cat/volcopy/:dataKey', {
36         templateUrl: './cat/volcopy/t_view',
37         controller: 'EditCtrl',
38         resolve : resolver
39     });
40
41     $routeProvider.when('/cat/volcopy/:dataKey/:mode', {
42         templateUrl: './cat/volcopy/t_view',
43         controller: 'EditCtrl',
44         resolve : resolver
45     });
46 })
47
48 .factory('itemSvc', 
49        ['egCore','$q',
50 function(egCore , $q) {
51
52     var service = {
53         currently_generating : false,
54         auto_gen_barcode : false,
55         barcode_checkdigit : false,
56         new_cp_id : 0,
57         new_cn_id : 0,
58         tree : {}, // holds lib->cn->copy hash stack
59         copies : [] // raw copy list
60     };
61
62     service.nextBarcode = function(bc) {
63         service.currently_generating = true;
64         return egCore.net.request(
65             'open-ils.cat',
66             'open-ils.cat.item.barcode.autogen',
67             egCore.auth.token(),
68             bc, 1, { checkdigit: service.barcode_checkdigit }
69         ).then(function(resp) { // get_barcodes
70             var evt = egCore.evt.parse(resp);
71             if (!evt) return resp[0];
72             return '';
73         });
74     };
75
76     service.checkBarcode = function(bc) {
77         if (!service.barcode_checkdigit) return true;
78         if (bc != Number(bc)) return false;
79         bc = bc.toString();
80         // "16.00" == Number("16.00"), but the . is bad.
81         // Throw out any barcode that isn't just digits
82         if (bc.search(/\D/) != -1) return false;
83         var last_digit = bc.substr(bc.length-1);
84         var stripped_barcode = bc.substr(0,bc.length-1);
85         return service.barcodeCheckdigit(stripped_barcode).toString() == last_digit;
86     };
87
88     service.barcodeCheckdigit = function(bc) {
89         var reverse_barcode = bc.toString().split('').reverse();
90         var check_sum = 0; var multiplier = 2;
91         for (var i = 0; i < reverse_barcode.length; i++) {
92             var digit = reverse_barcode[i];
93             var product = digit * multiplier; product = product.toString();
94             var temp_sum = 0;
95             for (var j = 0; j < product.length; j++) {
96                 temp_sum += Number( product[j] );
97             }
98             check_sum += Number( temp_sum );
99             multiplier = ( multiplier == 2 ? 1 : 2 );
100         }
101         check_sum = check_sum.toString();
102         var next_multiple_of_10 = (check_sum.match(/(\d*)\d$/)[1] * 10) + 10;
103         var check_digit = next_multiple_of_10 - Number(check_sum); if (check_digit == 10) check_digit = 0;
104         return check_digit;
105     };
106
107     // returns a promise resolved with the list of circ mods
108     service.get_classifications = function() {
109         if (egCore.env.acnc)
110             return $q.when(egCore.env.acnc.list);
111
112         return egCore.pcrud.retrieveAll('acnc', null, {atomic : true})
113         .then(function(list) {
114             egCore.env.absorbList(list, 'acnc');
115             return list;
116         });
117     };
118
119     service.get_prefixes = function(org) {
120         return egCore.pcrud.search('acnp',
121             {owning_lib : egCore.org.fullPath(org, true)},
122             {order_by : { acnp : 'label_sortkey' }}, {atomic : true}
123         );
124
125     };
126
127     service.get_statcats = function(orgs) {
128         return egCore.pcrud.search('asc',
129             {owner : orgs},
130             { flesh : 1,
131               flesh_fields : {
132                 asc : ['owner','entries']
133               }
134             },
135             { atomic : true }
136         );
137     };
138
139     service.get_locations = function(orgs) {
140         return egCore.pcrud.search('acpl',
141             {owning_lib : orgs, deleted : 'f'},
142             {
143                 flesh : 1,
144                 flesh_fields : {
145                     acpl : ['owning_lib']
146                 },
147                 order_by : { acpl : 'name' }
148             },
149             {atomic : true}
150         );
151     };
152
153     service.get_suffixes = function(org) {
154         return egCore.pcrud.search('acns',
155             {owning_lib : egCore.org.fullPath(org, true)},
156             {order_by : { acns : 'label_sortkey' }}, {atomic : true}
157         );
158
159     };
160
161     service.get_magic_statuses = function() {
162         /* TODO: make these more configurable per lp1616170 */
163         return $q.when([
164              1  /* Checked out */
165             ,3  /* Lost */
166             ,6  /* In transit */
167             ,8  /* On holds shelf */
168             ,16 /* Long overdue */
169             ,18 /* Canceled Transit */
170         ]);
171     }
172
173     service.get_statuses = function() {
174         if (egCore.env.ccs)
175             return $q.when(egCore.env.ccs.list);
176
177         return egCore.pcrud.retrieveAll('ccs', {order_by : { ccs : 'name' }}, {atomic : true}).then(
178             function(list) {
179                 egCore.env.absorbList(list, 'ccs');
180                 return list;
181             }
182         );
183
184     };
185
186     service.get_circ_mods = function() {
187         if (egCore.env.ccm)
188             return $q.when(egCore.env.ccm.list);
189
190         return egCore.pcrud.retrieveAll('ccm', {}, {atomic : true}).then(
191             function(list) {
192                 egCore.env.absorbList(list, 'ccm');
193                 return list;
194             }
195         );
196
197     };
198
199     service.get_circ_types = function() {
200         if (egCore.env.citm)
201             return $q.when(egCore.env.citm.list);
202
203         return egCore.pcrud.retrieveAll('citm', {}, {atomic : true}).then(
204             function(list) {
205                 egCore.env.absorbList(list, 'citm');
206                 return list;
207             }
208         );
209
210     };
211
212     service.get_age_protects = function() {
213         if (egCore.env.crahp)
214             return $q.when(egCore.env.crahp.list);
215
216         return egCore.pcrud.retrieveAll('crahp', {}, {atomic : true}).then(
217             function(list) {
218                 egCore.env.absorbList(list, 'crahp');
219                 return list;
220             }
221         );
222
223     };
224
225     service.get_floating_groups = function() {
226         if (egCore.env.cfg)
227             return $q.when(egCore.env.cfg.list);
228
229         return egCore.pcrud.retrieveAll('cfg', {}, {atomic : true}).then(
230             function(list) {
231                 egCore.env.absorbList(list, 'cfg');
232                 return list;
233             }
234         );
235
236     };
237
238     service.bmp_parts = {};
239     service.get_parts = function(rec) {
240         if (service.bmp_parts[rec])
241             return $q.when(service.bmp_parts[rec]);
242
243         return egCore.pcrud.search('bmp',
244             {record : rec, deleted : 'f'},
245             null, {atomic : true}
246         ).then(function(list) {
247             service.bmp_parts[rec] = list;
248             return list;
249         });
250
251     };
252
253     service.get_acp_templates = function() {
254         // Already downloaded for this user? Return local copy. Changing users or logging out causes another download
255         // so users always have their own templates, and any changes made on other machines appear as expected.
256         if (egCore.hatch.getSessionItem('cat.copy.templates.usr') == egCore.auth.user().id()) {
257             return egCore.hatch.getItem('cat.copy.templates').then(function(templ) {
258                 return templ;
259             });
260         } else {
261             // this can be disabled for debugging to force a re-download and translation of test templates
262             egCore.hatch.setSessionItem('cat.copy.templates.usr', egCore.auth.user().id());
263             return service.load_remote_acp_templates();
264         }
265
266     };
267
268     service.save_acp_templates = function(t) {
269         egCore.hatch.setItem('cat.copy.templates', t);
270         egCore.net.request('open-ils.actor', 'open-ils.actor.patron.settings.update',
271             egCore.auth.token(), egCore.auth.user().id(), { "webstaff.cat.copy.templates": t });
272         // console.warn('Saved ' + JSON.stringify({"webstaff.cat.copy.templates": t}));
273     };
274
275     service.load_remote_acp_templates = function() {
276         // After the XUL Client is completely removed everything related
277         // to staff_client.copy_editor.templates and convert_xul_templates
278         // can be thrown away.
279         return egCore.net.request('open-ils.actor', 'open-ils.actor.patron.settings.retrieve.authoritative',
280             egCore.auth.token(), egCore.auth.user().id(),
281             ['webstaff.cat.copy.templates','staff_client.copy_editor.templates']).then(function(settings) {
282                 if (settings['webstaff.cat.copy.templates']) {
283                     egCore.hatch.setItem('cat.copy.templates', settings['webstaff.cat.copy.templates']);
284                     return settings['webstaff.cat.copy.templates'];
285                 } else {
286                     if (settings['staff_client.copy_editor.templates']) {
287                         var new_templ = service.convert_xul_templates(settings['staff_client.copy_editor.templates']);
288                         egCore.hatch.setItem('cat.copy.templates', new_templ);
289                         // console.warn('Saving: ' + JSON.stringify({'webstaff.cat.copy.templates' : new_templ}));
290                         egCore.net.request('open-ils.actor', 'open-ils.actor.patron.settings.update',
291                             egCore.auth.token(), egCore.auth.user().id(), {'webstaff.cat.copy.templates' : new_templ});
292                         return new_templ;
293                     }
294                 }
295                 return {};
296         });
297     };
298
299     service.convert_xul_templates = function(xultempl) {
300         var conv_templ = {};
301         var templ_names = Object.keys(xultempl);
302         var name;
303         var xul_t;
304         var curr_templ;
305         var stat_cats;
306         var fields;
307         var curr_field;
308         var tmp_val;
309         var i, j;
310
311         if (templ_names) {
312             for (i=0; i < templ_names.length; i++) {
313                 name = templ_names[i];
314                 curr_templ = {};
315                 stat_cats = {};
316                 xul_t  = xultempl[name];
317                 fields = Object.keys(xul_t);
318
319                 if (fields.length > 0) {
320                     for (j=0; j < fields.length; j++) {
321                         curr_field = xul_t[fields[j]];
322                         var field_name = curr_field["field"];
323
324                         if ( field_name == null ) { continue; }
325                         if ( curr_field["value"] == "<HACK:KLUDGE:NULL>" ) { continue; }
326
327                         // floating changed from a boolean to an integer at one point;
328                         // take this opportunity to remove the boolean from any old templates
329                         if ( curr_field["type"] === "attribute" && field_name === "floating" ) {
330                             if ( curr_field["value"].match(/[tf]/) ) { continue; }
331                         }
332
333                         if ( curr_field["type"] === "stat_cat" ) {
334                             stat_cats[field_name] = parseInt(curr_field["value"]);
335                         } else {
336                             tmp_val = curr_field['value']; // so... some of the number fields are actually strings. Groovy.
337                             if ( tmp_val.toString().match(/^[-0-9.]+$/) && !(field_name.match(/(?:loan_duration|fine_level)/))) {
338                                 tmp_val = parseFloat(tmp_val);
339                             }
340
341                             if (field_name.match(/^batch_.*_menulist$/)) {
342                                 // special handling for volume fields
343                                 if (!("callnumber" in curr_templ)) curr_templ["callnumber"] = {};
344                                 if (field_name === "batch_class_menulist")  curr_templ["callnumber"]["classification"] = tmp_val;
345                                 if (field_name === "batch_prefix_menulist") curr_templ["callnumber"]["prefix"] = tmp_val;
346                                 if (field_name === "batch_suffix_menulist") curr_templ["callnumber"]["suffix"] = tmp_val;
347                             } else {
348                                 curr_templ[field_name] = tmp_val;
349                             }
350                         }
351                     }
352
353                     if ( (Object.keys(stat_cats)).length > 0 ) {
354                         curr_templ["statcats"] = stat_cats;
355                     }
356
357                     conv_templ[name] = curr_templ;
358                 }
359             }
360         }
361         return conv_templ;
362     };
363
364     service.flesh = {   
365         flesh : 3, 
366         flesh_fields : {
367             acp : ['call_number','parts','stat_cat_entries', 'notes', 'tags'],
368             acn : ['label_class','prefix','suffix'],
369             acptcm : ['tag']
370         }
371     }
372
373     service.addCopy = function (cp) {
374
375         if (!cp.parts()) cp.parts([]); // just in case...
376
377         var lib = cp.call_number().owning_lib();
378         var cn = cp.call_number().id();
379
380         if (!service.tree[lib]) service.tree[lib] = {};
381         if (!service.tree[lib][cn]) service.tree[lib][cn] = [];
382
383         service.tree[lib][cn].push(cp);
384         service.copies.push(cp);
385     }
386
387     service.checkDuplicateBarcode = function(bc, id) {
388         var final = false;
389         return egCore.pcrud.search('acp', { deleted : 'f', 'barcode' : bc, id : { '!=' : id } })
390             .then(
391                 function () { return final },
392                 function () { return final },
393                 function () { final = true; }
394             );
395     }
396
397     service.fetchIds = function(idList) {
398         service.tree = {}; // clear the tree on fetch
399         service.copies = []; // clear the copy list on fetch
400         return egCore.pcrud.search('acp', { 'id' : idList }, service.flesh).then(null,null,
401             function(copy) {
402                 service.addCopy(copy);
403             }
404         );
405     }
406
407     // create a new acp object with default values
408     // (both hard-coded and coming from OU settings)
409     service.generateNewCopy = function(callNumber, owningLib, isFastAdd, isNew) {
410         var cp = new egCore.idl.acp();
411         cp.id( --service.new_cp_id );
412         if (isNew) {
413             cp.isnew( true );
414         }
415         cp.circ_lib( owningLib );
416         cp.call_number( callNumber );
417         cp.deposit(0);
418         cp.price(0);
419         cp.deposit_amount(0);
420         cp.fine_level(2); // Normal
421         cp.loan_duration(2); // Normal
422         cp.location(1); // Stacks
423         cp.circulate('t');
424         cp.holdable('t');
425         cp.opac_visible('t');
426         cp.ref('f');
427         cp.mint_condition('t');
428         cp.empty_barcode = true;
429
430         var status_setting = isFastAdd ?
431             'cat.default_copy_status_fast' :
432             'cat.default_copy_status_normal';
433         egCore.org.settings(
434             [status_setting],
435             owningLib
436         ).then(function(set) {
437             var default_ccs = parseInt(set[status_setting]);
438             if (isNaN(default_ccs))
439                 default_ccs = (isFastAdd ? 0 : 5); // 0 is Available, 5 is In Process
440             cp.status(default_ccs);
441         });
442
443         return cp;
444     }
445
446     return service;
447 }])
448
449 .directive('stringToNumber', function() {
450     return {
451         require: 'ngModel',
452         link: function(scope, element, attrs, ngModel) {
453             var precision = attrs.precision || 0;
454             ngModel.$parsers.push(function(value) {
455                 return value;
456             });
457
458             function updateDisplay() {
459                 var value = parseFloat(ngModel.$viewValue);
460                 if ( isNaN(value) ) { return; }
461                     element.val(value.toFixed(precision));
462             }
463
464             ngModel.$formatters.push(function(value) {
465                 return parseFloat(value);
466             });
467
468             ngModel.$viewChangeListeners.push(updateDisplay);
469
470             ngModel.$render = function() {
471                 updateDisplay();
472             }
473         }
474     };
475 })
476
477 .directive("egVolCopyEdit", function () {
478     return {
479         restrict: 'E',
480         replace: true,
481         template:
482             '<div class="row">'+
483                 '<div class="col-xs-5" ng-class="{'+"'has-error'"+':barcode_has_error}">'+
484                     '<input id="{{callNumber.id()}}_{{copy.id()}}"'+
485                     ' eg-enter="nextBarcode(copy.id())" class="form-control"'+
486                     ' type="text" ng-model="barcode" ng-change="updateBarcode()"/>'+
487                     '<div class="label label-danger" ng-if="duplicate_barcode">{{duplicate_barcode_string}}</div>'+
488                     '<div class="label label-danger" ng-if="empty_barcode">{{empty_barcode_string}}</div>'+
489                 '</div>'+
490                 '<div class="col-xs-3"><input class="form-control" type="number" min="1" ng-model="copy_number" ng-change="updateCopyNo()"/></div>'+
491                 '<div class="col-xs-4"><eg-basic-combo-box eg-disabled="record == 0" list="parts" selected="part"></eg-basic-combo-box></div>'+
492             '</div>',
493
494         scope: { focusNext: "=", copy: "=", callNumber: "=", index: "@", record: "@" },
495         controller : ['$scope','itemSvc','egCore',
496             function ( $scope , itemSvc , egCore ) {
497                 $scope.new_part_id = 0;
498                 $scope.barcode_has_error = false;
499                 $scope.duplicate_barcode = false;
500                 $scope.empty_barcode = false;
501                 $scope.duplicate_barcode_string = window.duplicate_barcode_string;
502                 $scope.empty_barcode_string = window.empty_barcode_string;
503
504                 if (!$scope.copy.barcode()) $scope.copy.empty_barcode = true;
505
506                 $scope.nextBarcode = function (i) {
507                     $scope.focusNext(i, $scope.barcode);
508                 }
509
510                 $scope.updateBarcode = function () {
511                     if ($scope.barcode != '') {
512                         $scope.copy.empty_barcode = $scope.empty_barcode = false;
513                         $scope.barcode_has_error = !Boolean(itemSvc.checkBarcode($scope.barcode));
514                         itemSvc.checkDuplicateBarcode($scope.barcode, $scope.copy.id())
515                             .then(function (state) { $scope.copy.duplicate_barcode = $scope.duplicate_barcode = state });
516                     } else {
517                         $scope.copy.empty_barcode = $scope.empty_barcode = true;
518                     }
519                         
520                     $scope.copy.barcode($scope.barcode);
521                     $scope.copy.ischanged(1);
522                     if (itemSvc.currently_generating)
523                         $scope.focusNext($scope.copy.id(), $scope.barcode);
524                 };
525
526                 $scope.updateCopyNo = function () { $scope.copy.copy_number($scope.copy_number); $scope.copy.ischanged(1); };
527                 $scope.updatePart = function () {
528                     if ($scope.part) {
529                         var p = $scope.part_list.filter(function (x) {
530                             return x.label() == $scope.part
531                         });
532                         if (p.length > 0) { // preexisting part
533                             $scope.copy.parts(p)
534                         } else { // create one...
535                             var part = new egCore.idl.bmp();
536                             part.id( --$scope.new_part_id );
537                             part.isnew( true );
538                             part.label( $scope.part );
539                             part.record( $scope.callNumber.record() );
540                             $scope.copy.parts([part]);
541                             $scope.copy.ischanged(1);
542                         }
543                     } else {
544                         $scope.copy.parts([]);
545                     }
546                     $scope.copy.ischanged(1);
547                 }
548                 $scope.$watch('part', $scope.updatePart);
549
550                 $scope.barcode = $scope.copy.barcode();
551                 $scope.copy_number = $scope.copy.copy_number();
552
553                 if ($scope.copy.parts()) {
554                     $scope.part = $scope.copy.parts()[0];
555                     if ($scope.part) $scope.part = $scope.part.label();
556                 };
557
558                 $scope.parts = [];
559                 $scope.part_list = [];
560
561                 itemSvc.get_parts($scope.callNumber.record()).then(function(list){
562                     $scope.part_list = list;
563                     angular.forEach(list, function(p){ $scope.parts.push(p.label()) });
564                     $scope.parts = angular.copy($scope.parts);
565                 });
566
567             }
568         ]
569
570     }
571 })
572
573 .directive("egVolRow", function () {
574     return {
575         restrict: 'E',
576         replace: true,
577         transclude: true,
578         template:
579             '<div class="row">'+
580                 '<div class="col-xs-2">'+
581                     '<select ng-disabled="record == 0" class="form-control" ng-model="classification" ng-change="updateClassification()" ng-options="cl.name() for cl in classification_list"/>'+
582                 '</div>'+
583                 '<div class="col-xs-1">'+
584                     '<select ng-disabled="record == 0" class="form-control" ng-model="prefix" ng-change="updatePrefix()" ng-options="p.label() for p in prefix_list"/>'+
585                 '</div>'+
586                 '<div class="col-xs-2">'+
587                     '<input ng-disabled="record == 0" class="form-control" type="text" ng-change="updateLabel()" ng-model="label"/>'+
588                     '<div class="label label-danger" ng-if="empty_label">{{empty_label_string}}</div>'+
589                 '</div>'+
590                 '<div class="col-xs-1">'+
591                     '<select ng-disabled="record == 0" class="form-control" ng-model="suffix" ng-change="updateSuffix()" ng-options="s.label() for s in suffix_list"/>'+
592                 '</div>'+
593                 '<div ng-hide="onlyVols" class="col-xs-1"><input ng-disabled="record == 0" class="form-control" type="number" ng-model="copy_count" min="{{orig_copy_count}}" ng-change="changeCPCount()"></div>'+
594                 '<div ng-hide="onlyVols" class="col-xs-5">'+
595                     '<eg-vol-copy-edit record="{{record}}" ng-repeat="cp in copies track by idTracker(cp)" focus-next="focusNextBarcode" copy="cp" call-number="callNumber"></eg-vol-copy-edit>'+
596                 '</div>'+
597             '</div>',
598
599         scope: {focusNext: "=", allcopies: "=", copies: "=", onlyVols: "=", record: "@" },
600         controller : ['$scope','itemSvc','egCore',
601             function ( $scope , itemSvc , egCore ) {
602                 $scope.callNumber =  $scope.copies[0].call_number();
603                 if (!$scope.callNumber.label()) $scope.callNumber.emtpy_label = true;
604
605                 $scope.empty_label = false;
606                 $scope.empty_label_string = window.empty_label_string;
607
608                 $scope.idTracker = function (x) { if (x && x.id) return x.id() };
609
610                 // XXX $() is not working! arg
611                 $scope.focusNextBarcode = function (i, prev_bc) {
612                     var n;
613                     var yep = false;
614                     angular.forEach($scope.copies, function (cp) {
615                         if (n) return;
616
617                         if (cp.id() == i) {
618                             yep = true;
619                             return;
620                         }
621
622                         if (yep) n = cp.id();
623                     });
624
625                     if (n) {
626                         var next = '#' + $scope.callNumber.id() + '_' + n;
627                         var el = $(next);
628                         if (el) {
629                             if (!itemSvc.currently_generating) el.focus();
630                             if (prev_bc && itemSvc.auto_gen_barcode && el.val() == "") {
631                                 itemSvc.nextBarcode(prev_bc).then(function(bc){
632                                     el.focus();
633                                     el.val(bc);
634                                     el.trigger('change');
635                                 });
636                             } else {
637                                 itemSvc.currently_generating = false;
638                             }
639                         }
640                     } else {
641                         $scope.focusNext($scope.callNumber.id(),prev_bc)
642                     }
643                 }
644
645                 $scope.suffix_list = [];
646                 itemSvc.get_suffixes($scope.callNumber.owning_lib()).then(function(list){
647                     $scope.suffix_list = list;
648                     $scope.$watch('callNumber.suffix()', function (v) {
649                         if (angular.isObject(v)) v = v.id();
650                         $scope.suffix = $scope.suffix_list.filter( function (s) {
651                             return s.id() == v;
652                         })[0];
653                     });
654
655                 });
656                 $scope.updateSuffix = function () {
657                     angular.forEach($scope.copies, function(cp) {
658                         cp.call_number().suffix($scope.suffix);
659                         cp.call_number().ischanged(1);
660                     });
661                 }
662
663                 $scope.prefix_list = [];
664                 itemSvc.get_prefixes($scope.callNumber.owning_lib()).then(function(list){
665                     $scope.prefix_list = list;
666                     $scope.$watch('callNumber.prefix()', function (v) {
667                         if (angular.isObject(v)) v = v.id();
668                         $scope.prefix = $scope.prefix_list.filter(function (p) {
669                             return p.id() == v;
670                         })[0];
671                     });
672
673                 });
674                 $scope.updatePrefix = function () {
675                     angular.forEach($scope.copies, function(cp) {
676                         cp.call_number().prefix($scope.prefix);
677                         cp.call_number().ischanged(1);
678                     });
679                 }
680                 $scope.$watch('callNumber.owning_lib()', function(oldLib, newLib) {
681                     if (oldLib == newLib) return;
682                     var currentPrefix = $scope.callNumber.prefix();
683                     if (angular.isObject(currentPrefix)) currentPrefix = currentPrefix.id();
684                     itemSvc.get_prefixes($scope.callNumber.owning_lib()).then(function(list){
685                         $scope.prefix_list = list;
686                         var newPrefixId = $scope.prefix_list.filter(function (p) {
687                             return p.id() == currentPrefix;
688                         })[0] || -1;
689                         if (newPrefixId.id) newPrefixId = newPrefixId.id();
690                         $scope.prefix = $scope.prefix_list.filter(function (p) {
691                             return p.id() == newPrefixId;
692                         })[0];
693                         if ($scope.newPrefixId != currentPrefix) {
694                             $scope.callNumber.prefix($scope.prefix);
695                         }
696                     });
697                     var currentSuffix = $scope.callNumber.suffix();
698                     if (angular.isObject(currentSuffix)) currentSuffix = currentSuffix.id();
699                     itemSvc.get_suffixes($scope.callNumber.owning_lib()).then(function(list){
700                         $scope.suffix_list = list;
701                         var newSuffixId = $scope.suffix_list.filter(function (s) {
702                             return s.id() == currentSuffix;
703                         })[0] || -1;
704                         if (newSuffixId.id) newSuffixId = newSuffixId.id();
705                         $scope.suffix = $scope.suffix_list.filter(function (s) {
706                             return s.id() == newSuffixId;
707                         })[0];
708                         if ($scope.newSuffixId != currentSuffix) {
709                             $scope.callNumber.suffix($scope.suffix);
710                         }
711                     });
712                 });
713
714                 $scope.classification_list = [];
715                 itemSvc.get_classifications().then(function(list){
716                     $scope.classification_list = list;
717                     $scope.$watch('callNumber.label_class()', function (v) {
718                         if (angular.isObject(v)) v = v.id();
719                         $scope.classification = $scope.classification_list.filter(function (c) {
720                             return c.id() == v;
721                         })[0];
722                     });
723
724                 });
725                 $scope.updateClassification = function () {
726                     angular.forEach($scope.copies, function(cp) {
727                         cp.call_number().label_class($scope.classification);
728                         cp.call_number().ischanged(1);
729                     });
730                 }
731
732                 $scope.updateLabel = function () {
733                     if ($scope.label == '') {
734                         $scope.callNumber.empty_label = $scope.empty_label = true;
735                     } else {
736                         $scope.callNumber.empty_label = $scope.empty_label = false;
737                     }
738                     angular.forEach($scope.copies, function(cp) {
739                         cp.call_number().label($scope.label);
740                         cp.call_number().ischanged(1);
741                     });
742                 }
743
744                 $scope.$watch('callNumber.label()', function (v) {
745                     $scope.label = v;
746                 });
747
748                 $scope.prefix = $scope.callNumber.prefix();
749                 $scope.suffix = $scope.callNumber.suffix();
750                 $scope.classification = $scope.callNumber.label_class();
751                 $scope.label = $scope.callNumber.label();
752
753                 $scope.copy_count = $scope.copies.length;
754                 $scope.orig_copy_count = $scope.copy_count;
755
756                 $scope.changeCPCount = function () {
757                     while ($scope.copy_count > $scope.copies.length) {
758                         var cp = itemSvc.generateNewCopy(
759                             $scope.callNumber,
760                             $scope.callNumber.owning_lib(),
761                             $scope.fast_add,
762                             true
763                         );
764                         $scope.copies.push( cp );
765                         $scope.allcopies.push( cp );
766
767                     }
768
769                     if ($scope.copy_count >= $scope.orig_copy_count) {
770                         var how_many = $scope.copies.length - $scope.copy_count;
771                         if (how_many > 0) {
772                             var dead = $scope.copies.splice($scope.copy_count,how_many);
773                             $scope.callNumber.copies($scope.copies);
774
775                             // Trimming the global list is a bit more tricky
776                             angular.forEach( dead, function (d) {
777                                 angular.forEach( $scope.allcopies, function (l, i) { 
778                                     if (l === d) $scope.allcopies.splice(i,1);
779                                 });
780                             });
781                         }
782                     }
783                 }
784
785             }
786         ]
787
788     }
789 })
790
791 .directive("egVolEdit", function () {
792     return {
793         restrict: 'E',
794         replace: true,
795         template:
796             '<div class="row">'+
797                 '<div class="col-xs-1"><eg-org-selector alldisabled="{{record == 0}}" selected="owning_lib" disable-test="cant_have_vols"></eg-org-selector></div>'+
798                 '<div class="col-xs-1"><input ng-disabled="record == 0" class="form-control" type="number" min="{{orig_cn_count}}" ng-model="cn_count" ng-change="changeCNCount()"/></div>'+
799                 '<div class="col-xs-10">'+
800                     '<eg-vol-row only-vols="onlyVols" record="{{record}}"'+
801                         'ng-repeat="(cn,copies) in struct" '+
802                         'focus-next="focusNextFirst" copies="copies" allcopies="allcopies">'+
803                     '</eg-vol-row>'+
804                 '</div>'+
805             '</div>',
806
807         scope: { focusNext: "=", allcopies: "=", struct: "=", lib: "@", record: "@", onlyVols: "=" },
808         controller : ['$scope','itemSvc','egCore',
809             function ( $scope , itemSvc , egCore ) {
810                 $scope.first_cn = Object.keys($scope.struct)[0];
811                 $scope.full_cn = $scope.struct[$scope.first_cn][0].call_number();
812
813                 $scope.defaults = {};
814                 egCore.hatch.getItem('cat.copy.defaults').then(function(t) {
815                     if (t) {
816                         $scope.defaults = t;
817                     }
818                 });
819
820                 $scope.focusNextFirst = function(prev_cn,prev_bc) {
821                     var n;
822                     var yep = false;
823                     angular.forEach(Object.keys($scope.struct).sort(), function (cn) {
824                         if (n) return;
825
826                         if (cn == prev_cn) {
827                             yep = true;
828                             return;
829                         }
830
831                         if (yep) n = cn;
832                     });
833
834                     if (n) {
835                         var next = '#' + n + '_' + $scope.struct[n][0].id();
836                         var el = $(next);
837                         if (el) {
838                             if (!itemSvc.currently_generating) el.focus();
839                             if (prev_bc && itemSvc.auto_gen_barcode && el.val() == "") {
840                                 itemSvc.nextBarcode(prev_bc).then(function(bc){
841                                     el.focus();
842                                     el.val(bc);
843                                     el.trigger('change');
844                                 });
845                             } else {
846                                 itemSvc.currently_generating = false;
847                             }
848                         }
849                     } else {
850                         $scope.focusNext($scope.lib, prev_bc);
851                     }
852                 }
853
854                 $scope.cn_count = Object.keys($scope.struct).length;
855                 $scope.orig_cn_count = $scope.cn_count;
856
857                 $scope.owning_lib = egCore.org.get($scope.lib);
858                 $scope.$watch('owning_lib', function (oldLib, newLib) {
859                     if (oldLib == newLib) return;
860                     angular.forEach( Object.keys($scope.struct), function (cn) {
861                         $scope.struct[cn][0].call_number().owning_lib( $scope.owning_lib.id() );
862                         $scope.struct[cn][0].call_number().ischanged(1);
863                     });
864                 });
865
866                 $scope.cant_have_vols = function (id) { return !egCore.org.CanHaveVolumes(id); };
867
868                 $scope.$watch('cn_count', function (n) {
869                     var o = Object.keys($scope.struct).length;
870                     if (n > o) { // adding
871                         for (var i = o; o < n; o++) {
872                             var cn = new egCore.idl.acn();
873                             cn.id( --itemSvc.new_cn_id );
874                             cn.isnew( true );
875                             cn.prefix( $scope.defaults.prefix || -1 );
876                             cn.suffix( $scope.defaults.suffix || -1 );
877                             cn.label_class( $scope.defaults.classification || 1 );
878                             cn.owning_lib( $scope.owning_lib.id() );
879                             cn.record( $scope.full_cn.record() );
880
881                             var cp = itemSvc.generateNewCopy(
882                                 cn,
883                                 $scope.owning_lib.id(),
884                                 $scope.fast_add,
885                                 true
886                             );
887
888                             $scope.struct[cn.id()] = [cp];
889                             $scope.allcopies.push(cp);
890                             if (!$scope.defaults.classification) {
891                                 egCore.org.settings(
892                                     ['cat.default_classification_scheme'],
893                                     cn.owning_lib()
894                                 ).then(function (val) {
895                                     cn.label_class(val['cat.default_classification_scheme']);
896                                 });
897                             }
898                         }
899                     } else if (n < o && n >= $scope.orig_cn_count) { // removing
900                         var how_many = o - n;
901                         var list = Object
902                                 .keys($scope.struct)
903                                 .sort(function(a, b){return parseInt(a)-parseInt(b)})
904                                 .filter(function(x){ return parseInt(x) <= 0 });
905                         for (var i = 0; i < how_many; i++) {
906                             // Trimming the global list is a bit more tricky
907                             angular.forEach($scope.struct[list[i]], function (d) {
908                                 angular.forEach( $scope.allcopies, function (l, j) { 
909                                     if (l === d) $scope.allcopies.splice(j,1);
910                                 });
911                             });
912                             delete $scope.struct[list[i]];
913                         }
914                     }
915                 });
916             }
917         ]
918
919     }
920 })
921
922 /**
923  * Edit controller!
924  */
925 .controller('EditCtrl', 
926        ['$scope','$q','$window','$routeParams','$location','$timeout','egCore','egNet','egGridDataProvider','itemSvc','$uibModal',
927 function($scope , $q , $window , $routeParams , $location , $timeout , egCore , egNet , egGridDataProvider , itemSvc , $uibModal) {
928
929     $scope.forms = {}; // Accessed by t_attr_edit.tt2
930     $scope.i18n = egCore.i18n;
931
932     $scope.defaults = { // If defaults are not set at all, allow everything
933         barcode_checkdigit : false,
934         auto_gen_barcode : false,
935         statcats : true,
936         copy_notes : true,
937         copy_tags : true,
938         attributes : {
939             status : true,
940             loan_duration : true,
941             fine_level : true,
942             cost : true,
943             alerts : true,
944             deposit : true,
945             deposit_amount : true,
946             opac_visible : true,
947             price : true,
948             circulate : true,
949             mint_condition : true,
950             circ_lib : true,
951             ref : true,
952             circ_modifier : true,
953             circ_as_type : true,
954             location : true,
955             holdable : true,
956             age_protect : true,
957             floating : true,
958             alert_message : true
959         }
960     };
961
962     $scope.new_lib_to_add = egCore.org.get(egCore.auth.user().ws_ou());
963     $scope.changeNewLib = function (org) {
964         $scope.new_lib_to_add = org;
965     }
966     $scope.addLibToStruct = function () {
967         var newLib = $scope.new_lib_to_add;
968         var cn = new egCore.idl.acn();
969         cn.id( --itemSvc.new_cn_id );
970         cn.isnew( true );
971         cn.prefix( $scope.defaults.prefix || -1 );
972         cn.suffix( $scope.defaults.suffix || -1 );
973         cn.label_class( $scope.defaults.classification || 1 );
974         cn.owning_lib( newLib.id() );
975         cn.record( $scope.record_id );
976
977         var cp = itemSvc.generateNewCopy(
978             cn,
979             newLib.id(),
980             $scope.fast_add,
981             true
982         );
983
984         $scope.data.addCopy(cp);
985
986         if (!$scope.defaults.classification) {
987             egCore.org.settings(
988                 ['cat.default_classification_scheme'],
989                 cn.owning_lib()
990             ).then(function (val) {
991                 cn.label_class(val['cat.default_classification_scheme']);
992             });
993         }
994     }
995
996     $scope.embedded = ($routeParams.mode && $routeParams.mode == 'embedded') ? true : false;
997     $scope.edit_templates = ($location.path().match(/edit_template/)) ? true : false;
998
999     $scope.saveDefaults = function () {
1000         egCore.hatch.setItem('cat.copy.defaults', $scope.defaults);
1001     }
1002
1003     $scope.fetchDefaults = function () {
1004         egCore.hatch.getItem('cat.copy.defaults').then(function(t) {
1005             if (t) {
1006                 $scope.defaults = t;
1007                 if (!$scope.batch) $scope.batch = {};
1008                 $scope.batch.classification = $scope.defaults.classification;
1009                 $scope.batch.prefix = $scope.defaults.prefix;
1010                 $scope.batch.suffix = $scope.defaults.suffix;
1011                 $scope.working.statcat_filter = $scope.defaults.statcat_filter;
1012                 if (
1013                         typeof $scope.defaults.statcat_filter == 'object' &&
1014                         Object.keys($scope.defaults.statcat_filter).length > 0
1015                    ) {
1016                     // want fieldmapper object here...
1017                     $scope.defaults.statcat_filter =
1018                          egCore.idl.Clone($scope.defaults.statcat_filter);
1019                     // ... and ID here
1020                     $scope.working.statcat_filter = $scope.defaults.statcat_filter.id();
1021                 }
1022                 if ($scope.defaults.always_volumes) $scope.show_vols = true;
1023                 if ($scope.defaults.barcode_checkdigit) itemSvc.barcode_checkdigit = true;
1024                 if ($scope.defaults.auto_gen_barcode) itemSvc.auto_gen_barcode = true;
1025             }
1026         });
1027     }
1028     $scope.fetchDefaults();
1029
1030     $scope.$watch('defaults.statcat_filter', function() {
1031         $scope.saveDefaults();
1032     });
1033     $scope.$watch('defaults.auto_gen_barcode', function (n,o) {
1034         itemSvc.auto_gen_barcode = n
1035     });
1036
1037     $scope.$watch('defaults.barcode_checkdigit', function (n,o) {
1038         itemSvc.barcode_checkdigit = n
1039     });
1040
1041     $scope.dirty = false;
1042     $scope.$watch('dirty',
1043         function(newVal, oldVal) {
1044             if (newVal && newVal != oldVal) {
1045                 $($window).on('beforeunload.edit', function(){
1046                     return 'There is unsaved data!'
1047                 });
1048             } else {
1049                 $($window).off('beforeunload.edit');
1050             }
1051         }
1052     );
1053
1054     $scope.only_vols = false;
1055     $scope.show_vols = true;
1056     $scope.show_copies = true;
1057
1058     $scope.tracker = function (x,f) { if (x) return x[f]() };
1059     $scope.idTracker = function (x) { if (x) return $scope.tracker(x,'id') };
1060     $scope.cant_have_vols = function (id) { return !egCore.org.CanHaveVolumes(id); };
1061
1062     $scope.orgById = function (id) { return egCore.org.get(id) }
1063     $scope.statusById = function (id) {
1064         return $scope.status_list.filter( function (s) { return s.id() == id } )[0];
1065     }
1066     $scope.locationById = function (id) {
1067         return $scope.location_cache[''+id];
1068     }
1069
1070     $scope.workingToComplete = function () {
1071         angular.forEach( $scope.workingGridControls.selectedItems(), function (c) {
1072             angular.forEach( itemSvc.copies, function (w, i) {
1073                 if (c === w)
1074                     $scope.completed_copies = $scope.completed_copies.concat(itemSvc.copies.splice(i,1));
1075             });
1076         });
1077
1078         return true;
1079     }
1080
1081     $scope.completeToWorking = function () {
1082         angular.forEach( $scope.completedGridControls.selectedItems(), function (c) {
1083             angular.forEach( $scope.completed_copies, function (w, i) {
1084                 if (c === w)
1085                     itemSvc.copies = itemSvc.copies.concat($scope.completed_copies.splice(i,1));
1086             });
1087         });
1088
1089         return true;
1090     }
1091
1092     createSimpleUpdateWatcher = function (field,exclude_copies_with_one_of_these_values) {
1093         return $scope.$watch('working.' + field, function () {
1094             var newval = $scope.working[field];
1095
1096             if (typeof newval != 'undefined') {
1097                 if (angular.isObject(newval)) { // we'll use the pkey
1098                     if (newval.id) newval = newval.id();
1099                     else if (newval.code) newval = newval.code();
1100                 }
1101
1102                 if (""+newval == "" || newval == null) {
1103                     $scope.working[field] = undefined;
1104                     newval = null;
1105                 }
1106
1107                 if ($scope.workingGridControls && $scope.workingGridControls.selectedItems) {
1108                     angular.forEach(
1109                         $scope.workingGridControls.selectedItems(),
1110                         function (cp) {
1111                             if (exclude_copies_with_one_of_these_values
1112                                 && exclude_copies_with_one_of_these_values.indexOf(cp[field](),0) > -1) {
1113                                 return;
1114                             }
1115                             if (cp[field]() !== newval) {
1116                                 cp[field](newval);
1117                                 cp.ischanged(1);
1118                                 $scope.dirty = true;
1119                             }
1120                         }
1121                     );
1122                 }
1123             }
1124         });
1125     }
1126
1127     $scope.working = {
1128         statcats: {},
1129         statcat_filter: undefined
1130     };
1131
1132     $scope.statcatUpdate = function (id) {
1133         var newval = $scope.working.statcats[id];
1134
1135         if (typeof newval != 'undefined') {
1136             if (angular.isObject(newval)) { // we'll use the pkey
1137                 newval = newval.id();
1138             }
1139     
1140             if (""+newval == "" || newval == null) {
1141                 $scope.working.statcats[id] = undefined;
1142                 newval = null;
1143             }
1144     
1145             if (!$scope.in_item_select && $scope.workingGridControls && $scope.workingGridControls.selectedItems) {
1146                 angular.forEach(
1147                     $scope.workingGridControls.selectedItems(),
1148                     function (cp) {
1149                         $scope.dirty = true;
1150
1151                         cp.stat_cat_entries(
1152                             angular.forEach( cp.stat_cat_entries(), function (e) {
1153                                 if (e.stat_cat() == id) { // mark deleted
1154                                     e.isdeleted(1);
1155                                 }
1156                             })
1157                         );
1158     
1159                         if (newval) {
1160                             var e = new egCore.idl.asce();
1161                             e.isnew( 1 );
1162                             e.stat_cat( id );
1163                             e.id(newval);
1164
1165                             cp.stat_cat_entries(
1166                                 cp.stat_cat_entries() ?
1167                                     cp.stat_cat_entries().concat([ e ]) :
1168                                     [ e ]
1169                             );
1170
1171                         }
1172
1173                         // trim out all deleted ones; the API used to
1174                         // do the update doesn't actually consult
1175                         // isdeleted for stat cat entries
1176                         cp.stat_cat_entries(
1177                             cp.stat_cat_entries().filter(function (e) {
1178                                 return !Boolean(e.isdeleted());
1179                             })
1180                         );
1181    
1182                         cp.ischanged(1);
1183                     }
1184                 );
1185             }
1186         }
1187     }
1188
1189     var dataKey = $routeParams.dataKey;
1190     console.debug('dataKey: ' + dataKey);
1191
1192     if ((dataKey && dataKey.length > 0) || $scope.edit_templates) {
1193
1194         $scope.templates = {};
1195         $scope.template_name = '';
1196         $scope.template_name_list = [];
1197
1198         $scope.fetchTemplates = function () {
1199             itemSvc.get_acp_templates().then(function(t) {
1200                 if (t) {
1201                     $scope.templates = t;
1202                     $scope.template_name_list = Object.keys(t).sort();
1203                 }
1204             });
1205             egCore.hatch.getItem('cat.copy.last_template').then(function(t) {
1206                 if (t) $scope.template_name = t;
1207             });
1208         }
1209         $scope.fetchTemplates();
1210
1211         $scope.applyTemplate = function (n) {
1212             angular.forEach($scope.templates[n], function (v,k) {
1213                 if (k == 'circ_lib') {
1214                     $scope.working[k] = egCore.org.get(v);
1215                 } else if (!angular.isObject(v)) {
1216                     $scope.working[k] = angular.copy(v);
1217                 } else {
1218                     angular.forEach(v, function (sv,sk) {
1219                         if (k == 'callnumber') {
1220                             angular.forEach(v, function (cnv,cnk) {
1221                                 $scope.batch[cnk] = cnv;
1222                             });
1223                             $scope.applyBatchCNValues();
1224                         } else {
1225                             $scope.working[k][sk] = angular.copy(sv);
1226                             if (k == 'statcats') $scope.statcatUpdate(sk);
1227                         }
1228                     });
1229                 }
1230             });
1231             egCore.hatch.setItem('cat.copy.last_template', n);
1232         }
1233
1234         $scope.copytab = 'working';
1235         $scope.tab = 'edit';
1236         $scope.summaryRecord = null;
1237         $scope.record_id = null;
1238         $scope.data = {};
1239         $scope.completed_copies = [];
1240         $scope.location_orgs = [];
1241         $scope.location_cache = {};
1242         $scope.statcats = [];
1243         if (!$scope.batch) $scope.batch = {};
1244
1245         $scope.applyBatchCNValues = function () {
1246             if ($scope.data.tree) {
1247                 angular.forEach($scope.data.tree, function(cn_hash) {
1248                     angular.forEach(cn_hash, function(copies) {
1249                         angular.forEach(copies, function(cp) {
1250                             if (typeof $scope.batch.classification != 'undefined' && $scope.batch.classification != '') {
1251                                 var label_class = $scope.classification_list.filter(function(p){ return p.id() == $scope.batch.classification })[0];
1252                                 cp.call_number().label_class(label_class);
1253                                 cp.call_number().ischanged(1);
1254                                 $scope.dirty = true;
1255                             }
1256                             if (typeof $scope.batch.prefix != 'undefined' && $scope.batch.prefix != '') {
1257                                 var prefix = $scope.prefix_list.filter(function(p){ return p.id() == $scope.batch.prefix })[0];
1258                                 cp.call_number().prefix(prefix);
1259                                 cp.call_number().ischanged(1);
1260                                 $scope.dirty = true;
1261                             }
1262                             if (typeof $scope.batch.label != 'undefined' && $scope.batch.label != '') {
1263                                 cp.call_number().label($scope.batch.label);
1264                                 cp.call_number().ischanged(1);
1265                                 $scope.dirty = true;
1266                             }
1267                             if (typeof $scope.batch.suffix != 'undefined' && $scope.batch.suffix != '') {
1268                                 var suffix = $scope.suffix_list.filter(function(p){ return p.id() == $scope.batch.suffix })[0];
1269                                 cp.call_number().suffix(suffix);
1270                                 cp.call_number().ischanged(1);
1271                                 $scope.dirty = true;
1272                             }
1273                         });
1274                     });
1275                 });
1276             }
1277         }
1278
1279         $scope.clearWorking = function () {
1280             angular.forEach($scope.working, function (v,k,o) {
1281                 if (!angular.isObject(v)) {
1282                     if (typeof v != 'undefined')
1283                         $scope.working[k] = undefined;
1284                 } else if (k != 'circ_lib') {
1285                     angular.forEach(v, function (sv,sk) {
1286                         if (typeof v != 'undefined')
1287                             $scope.working[k][sk] = undefined;
1288                     });
1289                 }
1290             });
1291             $scope.working.circ_lib = undefined; // special
1292         }
1293
1294         $scope.completedGridDataProvider = egGridDataProvider.instance({
1295             get : function(offset, count) {
1296                 //return provider.arrayNotifier(itemSvc.copies, offset, count);
1297                 return this.arrayNotifier($scope.completed_copies, offset, count);
1298             }
1299         });
1300
1301         $scope.completedGridControls = {};
1302
1303         $scope.workingGridDataProvider = egGridDataProvider.instance({
1304             get : function(offset, count) {
1305                 //return provider.arrayNotifier(itemSvc.copies, offset, count);
1306                 return this.arrayNotifier(itemSvc.copies, offset, count);
1307             }
1308         });
1309
1310         $scope.workingGridControls = {};
1311         $scope.add_vols_copies = false;
1312         $scope.is_fast_add = false;
1313
1314         egNet.request(
1315             'open-ils.actor',
1316             'open-ils.actor.anon_cache.get_value',
1317             dataKey, 'edit-these-copies'
1318         ).then(function (data) {
1319
1320             if (data) {
1321                 if (data.hide_vols && !$scope.defaults.always_volumes) $scope.show_vols = false;
1322                 if (data.hide_copies) {
1323                     $scope.show_copies = false;
1324                     $scope.only_vols = true;
1325                 }
1326
1327                 $scope.record_id = data.record_id;
1328
1329                 function fetchRaw () {
1330                     if (!$scope.only_vols) $scope.dirty = true;
1331                     $scope.add_vols_copies = true;
1332
1333                     /* data.raw data structure looks like this:
1334                      * [{
1335                      *      callnumber : $cn_id, // optional, to add a copy to a cn
1336                      *      owner      : $org, // optional, defaults to ws_ou
1337                      *      label      : $cn_label, // optional, to supply a label on a new cn
1338                      *      barcode    : $cp_barcode // optional, to supply a barcode on a new cp
1339                      *      fast_add   : boolean // optional, to specify whether this came
1340                      *                              in as a fast add
1341                      * },...]
1342                      * 
1343                      * All can be left out and a completely empty vol/copy combo will be vivicated.
1344                      */
1345
1346                     angular.forEach(
1347                         data.raw,
1348                         function (proto) {
1349                             if (proto.fast_add) $scope.is_fast_add = true;
1350                             if (proto.callnumber) {
1351                                 return egCore.pcrud.retrieve('acn', proto.callnumber)
1352                                 .then(function(cn) {
1353                                     var cp = new itemSvc.generateNewCopy(
1354                                         cn,
1355                                         proto.owner || egCore.auth.user().ws_ou(),
1356                                         $scope.is_fast_add,
1357                                         ((!$scope.only_vols) ? true : false)
1358                                     );
1359
1360                                     if (proto.barcode) {
1361                                         cp.barcode( proto.barcode );
1362                                         cp.empty_barcode = false;
1363                                     }
1364
1365                                     itemSvc.addCopy(cp)
1366                                 });
1367                             } else {
1368                                 var cn = new egCore.idl.acn();
1369                                 cn.id( --itemSvc.new_cn_id );
1370                                 cn.isnew( true );
1371                                 cn.prefix( $scope.defaults.prefix || -1 );
1372                                 cn.suffix( $scope.defaults.suffix || -1 );
1373                                 cn.owning_lib( proto.owner || egCore.auth.user().ws_ou() );
1374                                 cn.record( $scope.record_id );
1375                                 egCore.org.settings(
1376                                     ['cat.default_classification_scheme'],
1377                                     cn.owning_lib()
1378                                 ).then(function (val) {
1379                                     cn.label_class(
1380                                         $scope.defaults.classification ||
1381                                         val['cat.default_classification_scheme'] ||
1382                                         1
1383                                     );
1384                                     if (proto.label) {
1385                                         cn.label( proto.label );
1386                                     } else {
1387                                         egCore.net.request(
1388                                             'open-ils.cat',
1389                                             'open-ils.cat.biblio.record.marc_cn.retrieve',
1390                                             $scope.record_id,
1391                                             cn.label_class()
1392                                         ).then(function(cn_array) {
1393                                             if (cn_array.length > 0) {
1394                                                 for (var field in cn_array[0]) {
1395                                                     cn.label( cn_array[0][field] );
1396                                                     break;
1397                                                 }
1398                                             }
1399                                         });
1400                                     }
1401                                 });
1402
1403                                 var cp = new itemSvc.generateNewCopy(
1404                                     cn,
1405                                     proto.owner || egCore.auth.user().ws_ou(),
1406                                     $scope.is_fast_add,
1407                                     true
1408                                 );
1409
1410                                 if (proto.barcode) {
1411                                     cp.barcode( proto.barcode );
1412                                     cp.empty_barcode = false;
1413                                 }
1414
1415                                 itemSvc.addCopy(cp)
1416                             }
1417     
1418                         }
1419                     );
1420
1421                     return itemSvc.copies;
1422                 }
1423
1424                 if (data.copies && data.copies.length)
1425                     return itemSvc.fetchIds(data.copies).then(fetchRaw);
1426
1427                 return fetchRaw();
1428
1429             }
1430
1431         }).then( function() {
1432             $scope.data = itemSvc;
1433             $scope.workingGridDataProvider.refresh();
1434         });
1435
1436         $scope.can_save = false;
1437         function check_saveable () {
1438             var can_save = true;
1439             angular.forEach(
1440                 itemSvc.copies,
1441                 function (i) {
1442                     if (i.duplicate_barcode || i.empty_barcode || i.call_number().empty_label)
1443                         can_save = false;
1444                 }
1445             );
1446             if ($scope.forms.myForm && $scope.forms.myForm.$invalid) {
1447                 can_save = false;
1448             }
1449             $scope.can_save = can_save;
1450         }
1451
1452         $scope.disableSave = function () {
1453             check_saveable();
1454             return !$scope.can_save;
1455         }
1456
1457         $scope.focusNextFirst = function(prev_lib,prev_bc) {
1458             var n;
1459             var yep = false;
1460             angular.forEach(Object.keys($scope.data.tree).sort(), function (lib) {
1461                 if (n) return;
1462
1463                 if (lib == prev_lib) {
1464                     yep = true;
1465                     return;
1466                 }
1467
1468                 if (yep) n = lib;
1469             });
1470
1471             if (n) {
1472                 var first_cn = Object.keys($scope.data.tree[n])[0];
1473                 var next = '#' + first_cn + '_' + $scope.data.tree[n][first_cn][0].id();
1474                 var el = $(next);
1475                 if (el) {
1476                     if (!itemSvc.currently_generating) el.focus();
1477                     if (prev_bc && itemSvc.auto_gen_barcode && el.val() == "") {
1478                         itemSvc.nextBarcode(prev_bc).then(function(bc){
1479                             el.focus();
1480                             el.val(bc);
1481                             el.trigger('change');
1482                         });
1483                     } else {
1484                         itemSvc.currently_generating = false;
1485                     }
1486                 }
1487             }
1488         }
1489
1490         $scope.in_item_select = false;
1491         $scope.afterItemSelect = function() { $scope.in_item_select = false };
1492         $scope.handleItemSelect = function (item_list) {
1493             if (item_list && item_list.length > 0) {
1494                 $scope.in_item_select = true;
1495
1496                 angular.forEach(Object.keys($scope.defaults.attributes), function (attr) {
1497
1498                     var value_hash = {};
1499                     angular.forEach(item_list, function (item) {
1500                         if (item[attr]) {
1501                             var v = item[attr]()
1502                             if (angular.isObject(v)) {
1503                                 if (v.id) v = v.id();
1504                                 else if (v.code) v = v.code();
1505                             }
1506                             value_hash[v] = 1;
1507                         }
1508                     });
1509
1510                     if (Object.keys(value_hash).length == 1) {
1511                         if (attr == 'circ_lib') {
1512                             $scope.working[attr] = egCore.org.get(item_list[0][attr]());
1513                         } else {
1514                             $scope.working[attr] = item_list[0][attr]();
1515                         }
1516                     } else {
1517                         $scope.working[attr] = undefined;
1518                     }
1519                 });
1520
1521                 angular.forEach($scope.statcats, function (sc) {
1522
1523                     var counter = -1;
1524                     var value_hash = {};
1525                     var none = false;
1526                     angular.forEach(item_list, function (item) {
1527                         if (item.stat_cat_entries()) {
1528                             if (item.stat_cat_entries().length > 0) {
1529                                 var right_sc = item.stat_cat_entries().filter(function (e) {
1530                                     return e.stat_cat() == sc.id() && !Boolean(e.isdeleted());
1531                                 });
1532
1533                                 if (right_sc.length > 0) {
1534                                     value_hash[right_sc[0].id()] = right_sc[0].id();
1535                                 } else {
1536                                     none = true;
1537                                 }
1538                             }
1539                         } else {
1540                             none = true;
1541                         }
1542                     });
1543
1544                     if (!none && Object.keys(value_hash).length == 1) {
1545                         $scope.working.statcats[sc.id()] = value_hash[Object.keys(value_hash)[0]];
1546                     } else {
1547                         $scope.working.statcats[sc.id()] = undefined;
1548                     }
1549                 });
1550
1551             } else {
1552                 $scope.clearWorking();
1553             }
1554
1555         }
1556
1557         $scope.$watch('data.copies.length', function () {
1558             if ($scope.data.copies) {
1559                 var base_orgs = $scope.data.copies.map(function(cp){
1560                     return cp.circ_lib()
1561                 }).concat(
1562                     $scope.data.copies.map(function(cp){
1563                         return cp.call_number().owning_lib()
1564                     })
1565                 ).concat(
1566                     [egCore.auth.user().ws_ou()]
1567                 ).filter(function(e,i,a){
1568                     return a.lastIndexOf(e) === i;
1569                 });
1570
1571                 var all_orgs = [];
1572                 angular.forEach(base_orgs, function(o) {
1573                     all_orgs = all_orgs.concat( egCore.org.fullPath(o, true) );
1574                 });
1575
1576                 var final_orgs = all_orgs.filter(function(e,i,a){
1577                     return a.lastIndexOf(e) === i;
1578                 }).sort(function(a, b){return parseInt(a)-parseInt(b)});
1579
1580                 if ($scope.location_orgs.toString() != final_orgs.toString()) {
1581                     $scope.location_orgs = final_orgs;
1582                     if ($scope.location_orgs.length) {
1583                         itemSvc.get_locations($scope.location_orgs).then(function(list){
1584                             angular.forEach(list, function(l) {
1585                                 $scope.location_cache[ ''+l.id() ] = l;
1586                             });
1587                             $scope.location_list = list;
1588                         });
1589
1590                         $scope.statcat_filter_list = [];
1591                         angular.forEach($scope.location_orgs, function (o) {
1592                             $scope.statcat_filter_list.push(egCore.org.get(o));
1593                         });
1594
1595                         itemSvc.get_statcats($scope.location_orgs).then(function(list){
1596                             $scope.statcats = list;
1597                             angular.forEach($scope.statcats, function (s) {
1598
1599                                 if (!$scope.working)
1600                                     $scope.working = { statcats: {}, statcat_filter: undefined};
1601                                 if (!$scope.working.statcats)
1602                                     $scope.working.statcats = {};
1603
1604                                 if (!$scope.in_item_select) {
1605                                     $scope.working.statcats[s.id()] = undefined;
1606                                 }
1607                                 createStatcatUpdateWatcher(s.id());
1608                             });
1609                             $scope.in_item_select = false;
1610                             // do a refresh here to work around a race
1611                             // condition that can result in stat cats
1612                             // not being selected.
1613                             $scope.workingGridDataProvider.refresh();
1614                         });
1615                     }
1616                 }
1617             }
1618
1619             $scope.workingGridDataProvider.refresh();
1620         });
1621
1622         $scope.statcat_visible = function (sc_owner) {
1623             var visible = typeof $scope.working.statcat_filter === 'undefined' || !$scope.working.statcat_filter;
1624             angular.forEach(egCore.org.ancestors(sc_owner), function (ancestor_org) {
1625                 if ($scope.working.statcat_filter == ancestor_org.id())
1626                     visible = true;
1627             });
1628             return visible;
1629         }
1630
1631         $scope.suffix_list = [];
1632         itemSvc.get_suffixes(egCore.auth.user().ws_ou()).then(function(list){
1633             $scope.suffix_list = list;
1634         });
1635
1636         $scope.prefix_list = [];
1637         itemSvc.get_prefixes(egCore.auth.user().ws_ou()).then(function(list){
1638             $scope.prefix_list = list;
1639         });
1640
1641         $scope.classification_list = [];
1642         itemSvc.get_classifications().then(function(list){
1643             $scope.classification_list = list;
1644         });
1645
1646         $scope.$watch('completed_copies.length', function () {
1647             $scope.completedGridDataProvider.refresh();
1648         });
1649
1650         $scope.location_list = [];
1651         itemSvc.get_locations().then(function(list){
1652             $scope.location_list = list;
1653         });
1654         createSimpleUpdateWatcher('location');
1655
1656         $scope.status_list = [];
1657         itemSvc.get_magic_statuses().then(function(list){
1658             $scope.magic_status_list = list;
1659             createSimpleUpdateWatcher('status',$scope.magic_status_list);
1660         });
1661         itemSvc.get_statuses().then(function(list){
1662             $scope.status_list = list;
1663         });
1664
1665         $scope.circ_modifier_list = [];
1666         itemSvc.get_circ_mods().then(function(list){
1667             $scope.circ_modifier_list = list;
1668         });
1669         createSimpleUpdateWatcher('circ_modifier');
1670
1671         $scope.circ_type_list = [];
1672         itemSvc.get_circ_types().then(function(list){
1673             $scope.circ_type_list = list;
1674         });
1675         createSimpleUpdateWatcher('circ_as_type');
1676
1677         $scope.age_protect_list = [];
1678         itemSvc.get_age_protects().then(function(list){
1679             $scope.age_protect_list = list;
1680         });
1681         createSimpleUpdateWatcher('age_protect');
1682
1683         $scope.floating_list = [];
1684         itemSvc.get_floating_groups().then(function(list){
1685             $scope.floating_list = list;
1686         });
1687         createSimpleUpdateWatcher('floating');
1688
1689         createSimpleUpdateWatcher('circ_lib');
1690         createSimpleUpdateWatcher('circulate');
1691         createSimpleUpdateWatcher('holdable');
1692         createSimpleUpdateWatcher('fine_level');
1693         createSimpleUpdateWatcher('loan_duration');
1694         createSimpleUpdateWatcher('price');
1695         createSimpleUpdateWatcher('cost');
1696         createSimpleUpdateWatcher('deposit');
1697         createSimpleUpdateWatcher('deposit_amount');
1698         createSimpleUpdateWatcher('mint_condition');
1699         createSimpleUpdateWatcher('opac_visible');
1700         createSimpleUpdateWatcher('ref');
1701         createSimpleUpdateWatcher('alert_message');
1702
1703         $scope.saveCompletedCopies = function (and_exit) {
1704             var cnHash = {};
1705             var perCnCopies = {};
1706             angular.forEach( $scope.completed_copies, function (cp) {
1707                 var cn = cp.call_number();
1708                 var cn_cps = cp.call_number().copies();
1709                 cp.call_number().copies([]);
1710                 var cn_id = cp.call_number().id();
1711                 cp.call_number(cn_id); // prevent loops in JSON-ification
1712                 if (!cnHash[cn_id]) {
1713                     cnHash[cn_id] = egCore.idl.Clone(cn);
1714                     perCnCopies[cn_id] = [egCore.idl.Clone(cp)];
1715                 } else {
1716                     perCnCopies[cn_id].push(egCore.idl.Clone(cp));
1717                 }
1718                 cp.call_number(cn); // put the data back
1719                 cp.call_number().copies(cn_cps);
1720                 if (typeof cnHash[cn_id].prefix() == 'object')
1721                     cnHash[cn_id].prefix(cnHash[cn_id].prefix().id()); // un-object-ize some fields
1722                 if (typeof cnHash[cn_id].suffix() == 'object')
1723                     cnHash[cn_id].suffix(cnHash[cn_id].suffix().id()); // un-object-ize some fields
1724             });
1725
1726             angular.forEach(perCnCopies, function (v, k) {
1727                 cnHash[k].copies(v);
1728             });
1729
1730             cnList = [];
1731             angular.forEach(cnHash, function (v, k) {
1732                 cnList.push(v);
1733             });
1734
1735             egNet.request(
1736                 'open-ils.cat',
1737                 'open-ils.cat.asset.volume.fleshed.batch.update.override',
1738                 egCore.auth.token(), cnList, 1, { auto_merge_vols : 1, create_parts : 1, return_copy_ids : 1 }
1739             ).then(function(copy_ids) {
1740                 if (and_exit) {
1741                     $scope.dirty = false;
1742                     if ($scope.defaults.print_item_labels) {
1743                         egCore.net.request(
1744                             'open-ils.actor',
1745                             'open-ils.actor.anon_cache.set_value',
1746                             null, 'print-labels-these-copies', {
1747                                 copies : copy_ids
1748                             }
1749                         ).then(function(key) {
1750                             if (key) {
1751                                 var url = egCore.env.basePath + 'cat/printlabels/' + key;
1752                                 $timeout(function() { $window.open(url, '_blank') }).then(
1753                                     function() { $timeout(function(){$window.close()}); }
1754                                 );
1755                             } else {
1756                                 alert('Could not create anonymous cache key!');
1757                             }
1758                         });
1759                     } else {
1760                         $timeout(function(){$window.close()});
1761                     }
1762                 }
1763             });
1764         }
1765
1766         $scope.saveAndContinue = function () {
1767             $scope.saveCompletedCopies(false);
1768         }
1769
1770         $scope.workingSaveAndExit = function () {
1771             $scope.workingToComplete();
1772             $scope.saveAndExit();
1773         }
1774
1775         $scope.saveAndExit = function () {
1776             $scope.saveCompletedCopies(true);
1777         }
1778
1779     }
1780
1781     $scope.copy_notes_dialog = function(copy_list) {
1782         var default_pub = Boolean($scope.defaults.copy_notes_pub);
1783         if (!angular.isArray(copy_list)) copy_list = [copy_list];
1784
1785         return $uibModal.open({
1786             templateUrl: './cat/volcopy/t_copy_notes',
1787             backdrop: 'static',
1788             animation: true,
1789             controller:
1790                    ['$scope','$uibModalInstance',
1791             function($scope , $uibModalInstance) {
1792                 $scope.focusNote = true;
1793                 $scope.note = {
1794                     creator : egCore.auth.user().id(),
1795                     title   : '',
1796                     value   : '',
1797                     pub     : default_pub,
1798                 };
1799
1800                 $scope.require_initials = false;
1801                 egCore.org.settings([
1802                     'ui.staff.require_initials.copy_notes'
1803                 ]).then(function(set) {
1804                     $scope.require_initials = Boolean(set['ui.staff.require_initials.copy_notes']);
1805                 });
1806
1807                 $scope.note_list = [];
1808                 if (copy_list.length == 1) {
1809                     $scope.note_list = copy_list[0].notes();
1810                 }
1811
1812                 $scope.ok = function(note) {
1813
1814                     if ($scope.initials) {
1815                         note.value = egCore.strings.$replace(
1816                             egCore.strings.COPY_NOTE_INITIALS, {
1817                             value : note.value, 
1818                             initials : $scope.initials,
1819                             ws_ou : egCore.org.get(
1820                                 egCore.auth.user().ws_ou()).shortname()
1821                         });
1822                     }
1823
1824                     angular.forEach(copy_list, function (cp) {
1825                         if (!angular.isArray(cp.notes())) cp.notes([]);
1826                         var n = new egCore.idl.acpn();
1827                         n.isnew(1);
1828                         n.creator(note.creator);
1829                         n.pub(note.pub);
1830                         n.title(note.title);
1831                         n.value(note.value);
1832                         n.owning_copy(cp.id());
1833                         cp.notes().push( n );
1834                     });
1835
1836                     $uibModalInstance.close();
1837                 }
1838
1839                 $scope.cancel = function($event) {
1840                     $uibModalInstance.dismiss();
1841                     $event.preventDefault();
1842                 }
1843             }]
1844         });
1845     }
1846
1847     $scope.copy_tags_dialog = function(copy_list) {
1848         if (!angular.isArray(copy_list)) copy_list = [copy_list];
1849
1850         return $uibModal.open({
1851             templateUrl: './cat/volcopy/t_copy_tags',
1852             backdrop: 'static',
1853             animation: true,
1854             controller:
1855                    ['$scope','$uibModalInstance',
1856             function($scope , $uibModalInstance) {
1857
1858                 $scope.tag_map = [];
1859                 var tag_hash = {};
1860                 var shared_tags = {};
1861                 angular.forEach(copy_list, function (cp) {
1862                     angular.forEach(cp.tags(), function(tag) {
1863                         if (!(tag.tag().id() in shared_tags)) {
1864                             shared_tags[tag.tag().id()] = 1;
1865                         } else {
1866                             shared_tags[tag.tag().id()]++;
1867                         }
1868                         if (!(tag.tag().id() in tag_hash)) {
1869                             tag_hash[tag.tag().id()] = tag;
1870                         }
1871                     });
1872                 });
1873                 angular.forEach(tag_hash, function(value, key) {
1874                     if (shared_tags[key] == copy_list.length) {
1875                         $scope.tag_map.push(value);
1876                     }
1877                 });
1878
1879                 $scope.tag_types = [];
1880                 egCore.pcrud.retrieveAll('cctt', {order_by : { cctt : 'label' }}, {atomic : true}).then(function(list) {
1881                     $scope.tag_types = list;
1882                     $scope.tag_type = $scope.tag_types[0].code(); // just pick a default
1883                 });
1884
1885                 $scope.getTags = function(val) {
1886                     return egCore.pcrud.search('acpt',
1887                         { 
1888                             owner :  egCore.org.fullPath(egCore.auth.user().ws_ou(), true),
1889                             label : { 'startwith' : {
1890                                         transform: 'evergreen.lowercase',
1891                                         value : [ 'evergreen.lowercase', val ]
1892                                     }},
1893                             tag_type : $scope.tag_type
1894                         },
1895                         { order_by : { 'acpt' : ['label'] } }, { atomic: true }
1896                     ).then(function(list) {
1897                         return list.map(function(item) {
1898                             return item.label();
1899                         });
1900                     });
1901                 }
1902
1903                 $scope.addTag = function() {
1904                     var tagLabel = $scope.selectedLabel;
1905                     // clear the typeahead
1906                     $scope.selectedLabel = "";
1907
1908                     // first, check tags already associated with the copy
1909                     var foundMatch = false;
1910                     angular.forEach($scope.tag_map, function(tag) {
1911                         if (tag.tag().label() ==  tagLabel && tag.tag().tag_type() == $scope.tag_type) {
1912                             foundMatch = true;
1913                             if (tag.isdeleted()) tag.isdeleted(0); // just deleting the mapping
1914                         }
1915                     });
1916                     if (!foundMatch) {
1917                         egCore.pcrud.search('acpt',
1918                             { 
1919                                 owner : egCore.org.fullPath(egCore.auth.user().ws_ou(), true),
1920                                 label : tagLabel,
1921                                 tag_type : $scope.tag_type
1922                             },
1923                             { order_by : { 'acpt' : ['label'] } }, { atomic: true }
1924                         ).then(function(list) {
1925                             if (list.length > 0) {
1926                                 var newMap = new egCore.idl.acptcm();
1927                                 newMap.isnew(1);
1928                                 newMap.copy(copy_list[0].id());
1929                                 newMap.tag(egCore.idl.Clone(list[0]));
1930                                 $scope.tag_map.push(newMap);
1931                             } else {
1932                                 var newTag = new egCore.idl.acpt();
1933                                 newTag.isnew(1);
1934                                 newTag.owner(egCore.auth.user().ws_ou());
1935                                 newTag.label(tagLabel);
1936                                 newTag.pub('t');
1937                                 newTag.tag_type($scope.tag_type);
1938
1939                                 var newMap = new egCore.idl.acptcm();
1940                                 newMap.isnew(1);
1941                                 newMap.copy(copy_list[0].id());
1942                                 newMap.tag(newTag);
1943                                 $scope.tag_map.push(newMap);
1944                             }
1945                         });
1946                     }
1947                 }
1948
1949                 $scope.ok = function(note) {
1950                     // in the multi-item case, this works OK for
1951                     // adding new maps to existing tags, but doesn't handle
1952                     // all possibilities
1953                     angular.forEach(copy_list, function (cp) {
1954                         cp.tags($scope.tag_map);
1955                     });
1956                     $uibModalInstance.close();
1957                 }
1958
1959                 $scope.cancel = function($event) {
1960                     $uibModalInstance.dismiss();
1961                     $event.preventDefault();
1962                 }
1963             }]
1964         });
1965     }
1966
1967 }])
1968
1969 .directive("egVolTemplate", function () {
1970     return {
1971         restrict: 'E',
1972         replace: true,
1973         template: '<div ng-include="'+"'/eg/staff/cat/volcopy/t_attr_edit'"+'"></div>',
1974         scope: {
1975             editTemplates: '=',
1976         },
1977         controller : ['$scope','$window','itemSvc','egCore','ngToast',
1978             function ( $scope , $window , itemSvc , egCore , ngToast) {
1979
1980                 $scope.i18n = egCore.i18n;
1981
1982                 $scope.defaults = { // If defaults are not set at all, allow everything
1983                     barcode_checkdigit : false,
1984                     auto_gen_barcode : false,
1985                     statcats : true,
1986                     copy_notes : true,
1987                     copy_tags : true,
1988                     attributes : {
1989                         status : true,
1990                         loan_duration : true,
1991                         fine_level : true,
1992                         cost : true,
1993                         alerts : true,
1994                         deposit : true,
1995                         deposit_amount : true,
1996                         opac_visible : true,
1997                         price : true,
1998                         circulate : true,
1999                         mint_condition : true,
2000                         circ_lib : true,
2001                         ref : true,
2002                         circ_modifier : true,
2003                         circ_as_type : true,
2004                         location : true,
2005                         holdable : true,
2006                         age_protect : true,
2007                         floating : true
2008                     }
2009                 };
2010
2011                 $scope.fetchDefaults = function () {
2012                     egCore.hatch.getItem('cat.copy.defaults').then(function(t) {
2013                         if (t) {
2014                             $scope.defaults = t;
2015                             $scope.working.statcat_filter = $scope.defaults.statcat_filter;
2016                             if (
2017                                     typeof $scope.defaults.statcat_filter == 'object' &&
2018                                     Object.keys($scope.defaults.statcat_filter).length > 0
2019                                 ) {
2020                                 // want fieldmapper object here...
2021                                 $scope.defaults.statcat_filter =
2022                                     egCore.idl.Clone($scope.defaults.statcat_filter);
2023                                 // ... and ID here
2024                                 $scope.working.statcat_filter = $scope.defaults.statcat_filter.id();
2025                             }
2026                         }
2027                     });
2028                 }
2029                 $scope.fetchDefaults();
2030
2031                 $scope.dirty = false;
2032                 $scope.$watch('dirty',
2033                     function(newVal, oldVal) {
2034                         if (newVal && newVal != oldVal) {
2035                             $($window).on('beforeunload.template', function(){
2036                                 return 'There is unsaved template data!'
2037                             });
2038                         } else {
2039                             $($window).off('beforeunload.template');
2040                         }
2041                     }
2042                 );
2043
2044                 $scope.template_controls = true;
2045
2046                 $scope.fetchTemplates = function () {
2047                     itemSvc.get_acp_templates().then(function(t) {
2048                         if (t) {
2049                             $scope.templates = t;
2050                             $scope.template_name_list = Object.keys(t).sort();
2051                         }
2052                     });
2053                 }
2054                 $scope.fetchTemplates();
2055             
2056                 $scope.applyTemplate = function (n) {
2057                     angular.forEach($scope.templates[n], function (v,k) {
2058                         if (k == 'circ_lib') {
2059                             $scope.working[k] = egCore.org.get(v);
2060                         } else if (!angular.isObject(v)) {
2061                             $scope.working[k] = angular.copy(v);
2062                         } else {
2063                             angular.forEach(v, function (sv,sk) {
2064                                 if (!(k in $scope.working))
2065                                     $scope.working[k] = {};
2066                                 $scope.working[k][sk] = angular.copy(sv);
2067                             });
2068                         }
2069                     });
2070                     $scope.template_name = '';
2071                 }
2072
2073                 $scope.deleteTemplate = function (n) {
2074                     if (n) {
2075                         delete $scope.templates[n]
2076                         $scope.template_name_list = Object.keys($scope.templates).sort();
2077                         $scope.template_name = '';
2078                         itemSvc.save_acp_templates($scope.templates);
2079                         $scope.$parent.fetchTemplates();
2080                         ngToast.create(egCore.strings.VOL_COPY_TEMPLATE_SUCCESS_DELETE);
2081                     }
2082                 }
2083
2084                 $scope.saveTemplate = function (n) {
2085                     if (n) {
2086                         var tmpl = {};
2087             
2088                         angular.forEach($scope.working, function (v,k) {
2089                             if (angular.isObject(v)) { // we'll use the pkey
2090                                 if (v.id) v = v.id();
2091                                 else if (v.code) v = v.code();
2092                             }
2093             
2094                             tmpl[k] = v;
2095                         });
2096             
2097                         $scope.templates[n] = tmpl;
2098                         $scope.template_name_list = Object.keys($scope.templates).sort();
2099             
2100                         itemSvc.save_acp_templates($scope.templates);
2101                         $scope.$parent.fetchTemplates();
2102
2103                         $scope.dirty = false;
2104                     } else {
2105                         // save all templates, as we might do after an import
2106                         itemSvc.save_acp_templates($scope.templates);
2107                         $scope.$parent.fetchTemplates();
2108                     }
2109                     ngToast.create(egCore.strings.VOL_COPY_TEMPLATE_SUCCESS_SAVE);
2110                 }
2111             
2112                 $scope.templates = {};
2113                 $scope.imported_templates = { data : '' };
2114                 $scope.template_name = '';
2115                 $scope.template_name_list = [];
2116
2117                 $scope.$watch('imported_templates.data', function(newVal, oldVal) {
2118                     if (newVal && newVal != oldVal) {
2119                         try {
2120                             var newTemplates = JSON.parse(newVal);
2121                             if (!Object.keys(newTemplates).length) return;
2122                             angular.forEach(Object.keys(newTemplates), function (k) {
2123                                 $scope.templates[k] = newTemplates[k];
2124                             });
2125                             itemSvc.save_acp_templates($scope.templates);
2126                             $scope.fetchTemplates();
2127                         } catch (E) {
2128                             console.log('tried to import an invalid copy template file');
2129                         }
2130                     }
2131                 });
2132
2133                 $scope.tracker = function (x,f) { if (x) return x[f]() };
2134                 $scope.idTracker = function (x) { if (x) return $scope.tracker(x,'id') };
2135                 $scope.cant_have_vols = function (id) { return !egCore.org.CanHaveVolumes(id); };
2136             
2137                 $scope.orgById = function (id) { return egCore.org.get(id) }
2138                 $scope.statusById = function (id) {
2139                     return $scope.status_list.filter( function (s) { return s.id() == id } )[0];
2140                 }
2141                 $scope.locationById = function (id) {
2142                     return $scope.location_cache[''+id];
2143                 }
2144             
2145                 createSimpleUpdateWatcher = function (field) {
2146                     $scope.$watch('working.' + field, function () {
2147                         var newval = $scope.working[field];
2148             
2149                         if (typeof newval != 'undefined') {
2150                             $scope.dirty = true;
2151                             if (angular.isObject(newval)) { // we'll use the pkey
2152                                 if (newval.id) $scope.working[field] = newval.id();
2153                                 else if (newval.code) $scope.working[field] = newval.code();
2154                             }
2155             
2156                             if (""+newval == "" || newval == null) {
2157                                 $scope.working[field] = undefined;
2158                             }
2159             
2160                         }
2161                     });
2162                 }
2163             
2164                 $scope.working = {
2165                     statcats: {},
2166                     statcat_filter: undefined
2167                 };
2168             
2169                 $scope.statcat_visible = function (sc_owner) {
2170                     var visible = typeof $scope.working.statcat_filter === 'undefined' || !$scope.working.statcat_filter;
2171                     angular.forEach(egCore.org.ancestors(sc_owner), function (ancestor_org) {
2172                         if ($scope.working.statcat_filter == ancestor_org.id())
2173                             visible = true;
2174                     });
2175                     return visible;
2176                 }
2177
2178                 createStatcatUpdateWatcher = function (id) {
2179                     return $scope.$watch('working.statcats[' + id + ']', function () {
2180                         if ($scope.working.statcats) {
2181                             var newval = $scope.working.statcats[id];
2182                 
2183                             if (typeof newval != 'undefined') {
2184                                 $scope.dirty = true;
2185                                 if (angular.isObject(newval)) { // we'll use the pkey
2186                                     newval = newval.id();
2187                                 }
2188                 
2189                                 if (""+newval == "" || newval == null) {
2190                                     $scope.working.statcats[id] = undefined;
2191                                     newval = null;
2192                                 }
2193                 
2194                             }
2195                         }
2196                     });
2197                 }
2198
2199                 $scope.clearWorking = function () {
2200                     angular.forEach($scope.working, function (v,k,o) {
2201                         if (!angular.isObject(v)) {
2202                             if (typeof v != 'undefined')
2203                                 $scope.working[k] = undefined;
2204                         } else if (k != 'circ_lib') {
2205                             angular.forEach(v, function (sv,sk) {
2206                                 $scope.working[k][sk] = undefined;
2207                             });
2208                         }
2209                     });
2210                     $scope.working.circ_lib = undefined; // special
2211                     $scope.dirty = false;
2212                 }
2213
2214                 $scope.working = {};
2215                 $scope.location_orgs = [];
2216                 $scope.location_cache = {};
2217             
2218                 $scope.location_list = [];
2219                 itemSvc.get_locations(
2220                     egCore.org.fullPath( egCore.auth.user().ws_ou(), true )
2221                 ).then(function(list){
2222                     $scope.location_list = list;
2223                 });
2224                 createSimpleUpdateWatcher('location');
2225
2226                 $scope.statcat_filter_list = egCore.org.fullPath( egCore.auth.user().ws_ou() );
2227
2228                 $scope.statcats = [];
2229                 itemSvc.get_statcats(
2230                     egCore.org.fullPath( egCore.auth.user().ws_ou(), true )
2231                 ).then(function(list){
2232                     $scope.statcats = list;
2233                     angular.forEach($scope.statcats, function (s) {
2234
2235                         if (!$scope.working)
2236                             $scope.working = { statcats: {}, statcat_filter: undefined};
2237                         if (!$scope.working.statcats)
2238                             $scope.working.statcats = {};
2239
2240                         $scope.working.statcats[s.id()] = undefined;
2241                         createStatcatUpdateWatcher(s.id());
2242                     });
2243                 });
2244             
2245                 $scope.status_list = [];
2246                 itemSvc.get_magic_statuses().then(function(list){
2247                     $scope.magic_status_list = list;
2248                 });
2249                 itemSvc.get_statuses().then(function(list){
2250                     $scope.status_list = list;
2251                 });
2252                 createSimpleUpdateWatcher('status');
2253             
2254                 $scope.circ_modifier_list = [];
2255                 itemSvc.get_circ_mods().then(function(list){
2256                     $scope.circ_modifier_list = list;
2257                 });
2258                 createSimpleUpdateWatcher('circ_modifier');
2259             
2260                 $scope.circ_type_list = [];
2261                 itemSvc.get_circ_types().then(function(list){
2262                     $scope.circ_type_list = list;
2263                 });
2264                 createSimpleUpdateWatcher('circ_as_type');
2265             
2266                 $scope.age_protect_list = [];
2267                 itemSvc.get_age_protects().then(function(list){
2268                     $scope.age_protect_list = list;
2269                 });
2270                 createSimpleUpdateWatcher('age_protect');
2271             
2272                 createSimpleUpdateWatcher('circulate');
2273                 createSimpleUpdateWatcher('holdable');
2274                 createSimpleUpdateWatcher('fine_level');
2275                 createSimpleUpdateWatcher('loan_duration');
2276                 createSimpleUpdateWatcher('cost');
2277                 createSimpleUpdateWatcher('deposit');
2278                 createSimpleUpdateWatcher('deposit_amount');
2279                 createSimpleUpdateWatcher('mint_condition');
2280                 createSimpleUpdateWatcher('opac_visible');
2281                 createSimpleUpdateWatcher('ref');
2282                 createSimpleUpdateWatcher('alert_message');
2283
2284                 $scope.suffix_list = [];
2285                 itemSvc.get_suffixes(egCore.auth.user().ws_ou()).then(function(list){
2286                     $scope.suffix_list = list;
2287                 });
2288
2289                 $scope.prefix_list = [];
2290                 itemSvc.get_prefixes(egCore.auth.user().ws_ou()).then(function(list){
2291                     $scope.prefix_list = list;
2292                 });
2293
2294                 $scope.classification_list = [];
2295                 itemSvc.get_classifications().then(function(list){
2296                     $scope.classification_list = list;
2297                 });
2298
2299                 createSimpleUpdateWatcher('working.callnumber.classification');
2300                 createSimpleUpdateWatcher('working.callnumber.prefix');
2301                 createSimpleUpdateWatcher('working.callnumber.suffix');
2302             }
2303         ]
2304     }
2305 })
2306
2307