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