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