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