]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Cat.pm
added support for setting an org unit setting to disable auto-record deletion when...
[Evergreen.git] / Open-ILS / src / perlmods / OpenILS / Application / Cat.pm
1 use strict; use warnings;
2 package OpenILS::Application::Cat;
3 use OpenILS::Application::AppUtils;
4 use OpenILS::Application;
5 use OpenILS::Application::Cat::Utils;
6 use OpenILS::Application::Cat::Merge;
7 use base qw/OpenILS::Application/;
8 use Time::HiRes qw(time);
9 use OpenSRF::EX qw(:try);
10 use OpenSRF::Utils::JSON;
11 use OpenILS::Utils::Fieldmapper;
12 use OpenILS::Event;
13 use OpenILS::Const qw/:const/;
14
15 use XML::LibXML;
16 use Unicode::Normalize;
17 use Data::Dumper;
18 use OpenILS::Utils::FlatXML;
19 use OpenILS::Utils::CStoreEditor q/:funcs/;
20 use OpenILS::Perm;
21 use OpenSRF::Utils::SettingsClient;
22 use OpenSRF::Utils::Logger qw($logger);
23 use OpenSRF::AppSession;
24
25 my $apputils = "OpenILS::Application::AppUtils";
26
27 my $utils = "OpenILS::Application::Cat::Utils";
28 my $U = "OpenILS::Application::AppUtils";
29
30 my $conf;
31
32 my %marctemplates;
33
34 sub entityize { 
35         my $stuff = shift;
36         my $form = shift || "";
37
38         if ($form eq 'D') {
39                 $stuff = NFD($stuff);
40         } else {
41                 $stuff = NFC($stuff);
42         }
43
44         $stuff =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
45         return $stuff;
46 }
47
48 __PACKAGE__->register_method(
49         method  => "retrieve_marc_template",
50         api_name        => "open-ils.cat.biblio.marc_template.retrieve",
51         notes           => <<"  NOTES");
52         Returns a MARC 'record tree' based on a set of pre-defined templates.
53         Templates include : book
54         NOTES
55
56 sub retrieve_marc_template {
57         my( $self, $client, $type ) = @_;
58         return $marctemplates{$type} if defined($marctemplates{$type});
59         $marctemplates{$type} = _load_marc_template($type);
60         return $marctemplates{$type};
61 }
62
63 __PACKAGE__->register_method(
64         method => 'fetch_marc_template_types',
65         api_name => 'open-ils.cat.marc_template.types.retrieve'
66 );
67
68 my $marc_template_files;
69
70 sub fetch_marc_template_types {
71         my( $self, $conn ) = @_;
72         __load_marc_templates();
73         return [ keys %$marc_template_files ];
74 }
75
76 sub __load_marc_templates {
77         return if $marc_template_files;
78         if(!$conf) { $conf = OpenSRF::Utils::SettingsClient->new; }
79
80         $marc_template_files = $conf->config_value(                                     
81                 "apps", "open-ils.cat","app_settings", "marctemplates" );
82
83         $logger->info("Loaded marc templates: " . Dumper($marc_template_files));
84 }
85
86 sub _load_marc_template {
87         my $type = shift;
88
89         __load_marc_templates();
90
91         my $template = $$marc_template_files{$type};
92         open( F, $template ) or 
93                 throw OpenSRF::EX::ERROR ("Unable to open MARC template file: $template : $@");
94
95         my @xml = <F>;
96         close(F);
97         my $xml = join('', @xml);
98
99         return XML::LibXML->new->parse_string($xml)->documentElement->toString;
100 }
101
102 my $__bib_sources;
103 sub bib_source_from_name {
104         my $name = shift;
105         $logger->debug("searching for bib source: $name");
106
107         fetch_bib_sources();
108
109         my ($s) = grep { lc($_->source) eq lc($name) } @$__bib_sources;
110
111         return $s->id if $s;
112         return undef;
113 }
114
115
116 __PACKAGE__->register_method(
117         method => 'fetch_bib_sources',
118         api_name => 'open-ils.cat.bib_sources.retrieve.all');
119
120 sub fetch_bib_sources {
121         $__bib_sources = new_editor()->retrieve_all_config_bib_source()
122                 unless $__bib_sources;
123         return $__bib_sources;
124 }
125
126
127
128 __PACKAGE__->register_method(
129         method  => "create_record_xml",
130         api_name        => "open-ils.cat.biblio.record.xml.create.override",
131         signature       => q/@see open-ils.cat.biblio.record.xml.create/);
132
133 __PACKAGE__->register_method(
134         method          => "create_record_xml",
135         api_name                => "open-ils.cat.biblio.record.xml.create",
136         signature       => q/
137                 Inserts a new biblio with the given XML
138         /
139 );
140
141 sub create_record_xml {
142         my( $self, $client, $login, $xml, $source ) = @_;
143
144         my $override = 1 if $self->api_name =~ /override/;
145
146         my( $user_obj, $evt ) = $U->checksesperm($login, 'CREATE_MARC');
147         return $evt if $evt;
148
149         $logger->activity("user ".$user_obj->id." creating new MARC record");
150
151         my $meth = $self->method_lookup("open-ils.cat.biblio.record.xml.import");
152
153         $meth = $self->method_lookup(
154                 "open-ils.cat.biblio.record.xml.import.override") if $override;
155
156         my ($s) = $meth->run($login, $xml, $source);
157         return $s;
158 }
159
160
161
162 __PACKAGE__->register_method(
163         method  => "biblio_record_replace_marc",
164         api_name        => "open-ils.cat.biblio.record.xml.update",
165         argc            => 3, 
166         signature       => q/
167                 Updates the XML for a given biblio record.
168                 This does not change any other aspect of the record entry
169                 exception the XML, the editor, and the edit date.
170                 @return The update record object
171         /
172 );
173
174 __PACKAGE__->register_method(
175         method          => 'biblio_record_replace_marc',
176         api_name                => 'open-ils.cat.biblio.record.marc.replace',
177         signature       => q/
178                 @param auth The authtoken
179                 @param recid The record whose MARC we're replacing
180                 @param newxml The new xml to use
181         /
182 );
183
184 __PACKAGE__->register_method(
185         method          => 'biblio_record_replace_marc',
186         api_name                => 'open-ils.cat.biblio.record.marc.replace.override',
187         signature       => q/@see open-ils.cat.biblio.record.marc.replace/
188 );
189
190 sub biblio_record_replace_marc  {
191         my( $self, $conn, $auth, $recid, $newxml, $source ) = @_;
192
193         warn "Updating MARC with xml\n$newxml\n";
194
195         my $e = new_editor(authtoken=>$auth, xact=>1);
196         return $e->die_event unless $e->checkauth;
197         return $e->die_event unless $e->allowed('CREATE_MARC', $e->requestor->ws_ou);
198
199         my $rec = $e->retrieve_biblio_record_entry($recid)
200                 or return $e->die_event;
201
202         my $fixtcn = 1 if $self->api_name =~ /replace/o;
203
204         # See if there is a different record in the database that has our TCN value
205         # If we're not updating the TCN, all we care about it the marcdoc
206         my $override = $self->api_name =~ /override/;
207
208    # XXX should .update even bother with the tcn_info if it's not going to replace it?
209    # there is the potential for returning a TCN_EXISTS event, even though no replacement happens
210
211         my( $tcn, $tsource, $marcdoc, $evt);
212
213     if($fixtcn or $override) {
214
215             ($tcn, $tsource, $marcdoc, $evt) = 
216                     _find_tcn_info($e, $newxml, $override, $recid);
217
218             return $evt if $evt;
219
220                 $rec->tcn_value($tcn) if ($tcn);
221                 $rec->tcn_source($tsource);
222
223     } else {
224
225         $marcdoc = __make_marc_doc($newxml);
226     }
227
228
229
230         $rec->source(bib_source_from_name($source)) if $source;
231         $rec->editor($e->requestor->id);
232         $rec->edit_date('now');
233         $rec->marc( entityize( $marcdoc->documentElement->toString ) );
234
235         $logger->activity("user ".$e->requestor->id." replacing MARC for record $recid");
236
237         $e->update_biblio_record_entry($rec) or return $e->event;
238         $e->commit;
239
240         $conn->respond_complete($rec);
241
242         $U->simplereq(
243                 'open-ils.ingest',
244                 'open-ils.ingest.full.biblio.record', $recid );
245
246         return undef;
247 }
248
249
250
251
252 __PACKAGE__->register_method(
253         method  => "biblio_record_xml_import",
254         api_name        => "open-ils.cat.biblio.record.xml.import.override",
255         signature       => q/@see open-ils.cat.biblio.record.xml.import/);
256
257 __PACKAGE__->register_method(
258         method  => "biblio_record_xml_import",
259         api_name        => "open-ils.cat.biblio.record.xml.import",
260         notes           => <<"  NOTES");
261         Takes a marcxml record and imports the record into the database.  In this
262         case, the marcxml record is assumed to be a complete record (i.e. valid
263         MARC).  The title control number is taken from (whichever comes first)
264         tags 001, 039[ab], 020a, 022a, 010, 035a and whichever does not already exist
265         in the database.
266         user_session must have IMPORT_MARC permissions
267         NOTES
268
269
270 sub biblio_record_xml_import {
271         my( $self, $client, $authtoken, $xml, $source, $auto_tcn) = @_;
272
273         my $override = 1 if $self->api_name =~ /override/;
274     my $e = new_editor(xact=>1, authtoken=>$authtoken);
275     return $e->die_event unless $e->checkauth;
276     return $e->die_event unless $e->allowed('IMPORT_MARC', $e->requestor->ws_ou);
277
278         my( $evt, $tcn, $tcn_source, $marcdoc );
279
280         if( $auto_tcn ) {
281                 # auto_tcn forces a blank TCN value so the DB will have to generate one for us
282                 $marcdoc = __make_marc_doc($xml);
283         } else {
284                 ( $tcn, $tcn_source, $marcdoc, $evt ) = _find_tcn_info($e, $xml, $override);
285                 return $evt if $evt;
286         }
287
288         $logger->info("user ".$e->requestor->id.
289                 " creating new biblio entry with tcn=$tcn and tcn_source $tcn_source");
290
291         my $record = Fieldmapper::biblio::record_entry->new;
292
293         $record->source(bib_source_from_name($source)) if $source;
294         $record->tcn_source($tcn_source);
295         $record->tcn_value($tcn) if ($tcn);
296         $record->creator($e->requestor->id);
297         $record->editor($e->requestor->id);
298         $record->create_date('now');
299         $record->edit_date('now');
300         $record->marc( entityize( $marcdoc->documentElement->toString ) );
301
302     $record = $e->create_biblio_record_entry($record) or return $e->die_event;
303         $logger->info("marc create/import created new record ".$record->id);
304
305     $e->commit;
306
307         $logger->debug("Sending record off to be ingested and indexed");
308
309         $client->respond_complete($record);
310
311         $U->simplereq(
312                 'open-ils.ingest',
313                 'open-ils.ingest.full.biblio.record', $record->id );
314
315         return undef;
316 }
317
318 sub __make_marc_doc {
319         my $xml = shift;
320         my $marcxml = XML::LibXML->new->parse_string( $xml );
321         $marcxml->documentElement->setNamespace( 
322                 "http://www.loc.gov/MARC21/slim", "marc", 1 );
323         $marcxml->documentElement->setNamespace("http://www.loc.gov/MARC21/slim");
324         return $marcxml;
325 }
326
327
328 sub _find_tcn_info { 
329         my $editor              = shift;
330         my $xml                 = shift;
331         my $override    = shift;
332         my $existing_rec        = shift || 0;
333
334         # parse the XML
335         my $marcxml = __make_marc_doc($xml);
336
337         my $xpath = '//marc:controlfield[@tag="001"]';
338         my $tcn = $marcxml->documentElement->findvalue($xpath);
339         $logger->info("biblio import located 001 (tcn) value of $tcn");
340
341         $xpath = '//marc:controlfield[@tag="003"]';
342         my $tcn_source = $marcxml->documentElement->findvalue($xpath) || "System Local";
343
344         if(my $rec = _tcn_exists($editor, $tcn, $tcn_source, $existing_rec) ) {
345
346                 my $origtcn = $tcn;
347                 $tcn = find_free_tcn( $marcxml, $editor, $existing_rec );
348
349                 # if we're overriding, try to find a different TCN to use
350                 if( $override ) {
351
352          # XXX Create ALLOW_ALT_TCN permission check support 
353
354                         $logger->info("tcn value $tcn already exists, attempting to override");
355
356                         if(!$tcn) {
357                                 return ( 
358                                         undef, 
359                                         undef, 
360                                         undef,
361                                         OpenILS::Event->new(
362                                                 'OPEN_TCN_NOT_FOUND', 
363                                                         payload => $marcxml->toString())
364                                         );
365                         }
366
367                 } else {
368
369                         $logger->warn("tcn value $origtcn already exists in import/create");
370
371                         # otherwise, return event
372                         return ( 
373                                 undef, 
374                                 undef, 
375                                 undef,
376                                 OpenILS::Event->new( 
377                                         'TCN_EXISTS', payload => { 
378                                                 dup_record      => $rec, 
379                                                 tcn                     => $origtcn,
380                                                 new_tcn         => $tcn
381                                                 }
382                                         )
383                                 );
384                 }
385         }
386
387         return ($tcn, $tcn_source, $marcxml);
388 }
389
390 sub find_free_tcn {
391
392         my $marcxml = shift;
393         my $editor = shift;
394         my $existing_rec = shift;
395
396         my $add_039 = 0;
397
398         my $xpath = '//marc:datafield[@tag="039"]/subfield[@code="a"]';
399         my ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
400         $xpath = '//marc:datafield[@tag="039"]/subfield[@code="b"]';
401         my $tcn_source = $marcxml->documentElement->findvalue($xpath) || "System Local";
402
403         if(_tcn_exists($editor, $tcn, $tcn_source, $existing_rec)) {
404                 $tcn = undef;
405         } else {
406                 $add_039++;
407         }
408
409
410         if(!$tcn) {
411                 $xpath = '//marc:datafield[@tag="020"]/subfield[@code="a"]';
412                 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
413                 $tcn_source = "ISBN";
414                 if(_tcn_exists($editor, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
415         }
416
417         if(!$tcn) { 
418                 $xpath = '//marc:datafield[@tag="022"]/subfield[@code="a"]';
419                 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
420                 $tcn_source = "ISSN";
421                 if(_tcn_exists($editor, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
422         }
423
424         if(!$tcn) {
425                 $xpath = '//marc:datafield[@tag="010"]';
426                 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
427                 $tcn_source = "LCCN";
428                 if(_tcn_exists($editor, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
429         }
430
431         if(!$tcn) {
432                 $xpath = '//marc:datafield[@tag="035"]/subfield[@code="a"]';
433                 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
434                 $tcn_source = "System Legacy";
435                 if(_tcn_exists($editor, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
436
437                 if($tcn) {
438                         $marcxml->documentElement->removeChild(
439                                 $marcxml->documentElement->findnodes( '//datafield[@tag="035"]' )
440                         );
441                 }
442         }
443
444         return undef unless $tcn;
445
446         if ($add_039) {
447                 my $df = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'datafield');
448                 $df->setAttribute( tag => '039' );
449                 $df->setAttribute( ind1 => ' ' );
450                 $df->setAttribute( ind2 => ' ' );
451                 $marcxml->documentElement->appendChild( $df );
452
453                 my $sfa = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'subfield');
454                 $sfa->setAttribute( code => 'a' );
455                 $sfa->appendChild( $marcxml->createTextNode( $tcn ) );
456                 $df->appendChild( $sfa );
457
458                 my $sfb = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'subfield');
459                 $sfb->setAttribute( code => 'b' );
460                 $sfb->appendChild( $marcxml->createTextNode( $tcn_source ) );
461                 $df->appendChild( $sfb );
462         }
463
464         return $tcn;
465 }
466
467
468
469 sub _tcn_exists {
470         my $editor = shift;
471         my $tcn = shift;
472         my $source = shift;
473         my $existing_rec = shift || 0;
474
475         if(!$tcn) {return 0;}
476
477         $logger->debug("tcn_exists search for tcn $tcn and source $source and id $existing_rec");
478
479         # XXX why does the source matter?
480 #       my $req = $session->request(      
481 #               { tcn_value => $tcn, tcn_source => $source, deleted => 'f' } );
482
483     my $recs = $editor->search_biblio_record_entry(
484         {tcn_value => $tcn, deleted => 'f', id => {'!=' => $existing_rec}}, {idlist =>1});
485
486         if(@$recs) {
487                 $logger->debug("_tcn_exists is true for tcn : $tcn ($source)");
488                 return $recs->[0];
489         }
490
491         $logger->debug("_tcn_exists is false for tcn : $tcn ($source)");
492         return 0;
493 }
494
495
496 __PACKAGE__->register_method(
497         method  => "biblio_record_record_metadata",
498         api_name        => "open-ils.cat.biblio.record.metadata.retrieve",
499     authoritative => 1,
500         argc            => 1, #(session_id, biblio_tree ) 
501         notes           => "Walks the tree and commits any changed nodes " .
502                                         "adds any new nodes, and deletes any deleted nodes",
503 );
504
505 sub biblio_record_record_metadata {
506         my( $self, $client, $authtoken, $ids ) = @_;
507
508         return [] unless $ids and @$ids;
509
510         my $editor = new_editor(authtoken => $authtoken);
511         return $editor->event unless $editor->checkauth;
512         return $editor->event unless $editor->allowed('VIEW_USER');
513
514         my @results;
515
516         for(@$ids) {
517                 return $editor->event unless 
518                         my $rec = $editor->retrieve_biblio_record_entry($_);
519                 $rec->creator($editor->retrieve_actor_user($rec->creator));
520                 $rec->editor($editor->retrieve_actor_user($rec->editor));
521                 $rec->clear_marc; # slim the record down
522                 push( @results, $rec );
523         }
524
525         return \@results;
526 }
527
528
529
530 __PACKAGE__->register_method(
531         method  => "biblio_record_marc_cn",
532         api_name        => "open-ils.cat.biblio.record.marc_cn.retrieve",
533         argc            => 1, #(bib id ) 
534 );
535
536 sub biblio_record_marc_cn {
537         my( $self, $client, $id ) = @_;
538
539         my $session = OpenSRF::AppSession->create("open-ils.cstore");
540         my $marc = $session
541                 ->request("open-ils.cstore.direct.biblio.record_entry.retrieve", $id )
542                 ->gather(1)
543                 ->marc;
544
545         my $doc = XML::LibXML->new->parse_string($marc);
546         $doc->documentElement->setNamespace( "http://www.loc.gov/MARC21/slim", "marc", 1 );
547         
548         my @res;
549         for my $tag ( qw/050 055 060 070 080 082 086 088 090 092 096 098 099/ ) {
550                 my @node = $doc->findnodes("//marc:datafield[\@tag='$tag']");
551                 for my $x (@node) {
552                         my $cn = $x->findvalue("marc:subfield[\@code='a' or \@code='b']");
553                         push @res, {$tag => $cn} if ($cn);
554                 }
555         }
556
557         return \@res
558 }
559
560 sub _get_id_by_userid {
561
562         my @users = @_;
563         my @ids;
564
565         my $session = OpenSRF::AppSession->create( "open-ils.cstore" );
566         my $request = $session->request( 
567                 "open-ils.cstore.direct.actor.user.search.atomic", { usrname => \@users } );
568
569         $request->wait_complete;
570         my $response = $request->recv();
571         if(!$request->complete) { 
572                 throw OpenSRF::EX::ERROR ("no response from cstore on user retrieve");
573         }
574
575         if(UNIVERSAL::isa( $response, "Error")){
576                 throw $response ($response);
577         }
578
579         for my $u (@{$response->content}) {
580                 next unless ref($u);
581                 push @ids, $u->id();
582         }
583
584         $request->finish;
585         $session->disconnect;
586         $session->kill_me();
587
588         return @ids;
589 }
590
591
592 # commits metadata objects to the db
593 sub _update_record_metadata {
594
595         my ($session, @docs ) = @_;
596
597         for my $doc (@docs) {
598
599                 my $user_obj = $doc->{user};
600                 my $docid = $doc->{docid};
601
602                 warn "Updating metata for doc $docid\n";
603
604                 my $request = $session->request( 
605                         "open-ils.storage.direct.biblio.record_entry.retrieve", $docid );
606                 my $record = $request->gather(1);
607
608                 warn "retrieved record\n";
609                 my ($id) = _get_id_by_userid($user_obj->usrname);
610
611                 warn "got $id from _get_id_by_userid\n";
612                 $record->editor($id);
613                 
614                 warn "Grabbed the record, updating and moving on\n";
615
616                 $request = $session->request( 
617                         "open-ils.storage.direct.biblio.record_entry.update", $record );
618                 $request->gather(1);
619         }
620
621         warn "committing metarecord update\n";
622
623         return 1;
624 }
625
626
627
628 __PACKAGE__->register_method(
629         method  => "orgs_for_title",
630     authoritative => 1,
631         api_name        => "open-ils.cat.actor.org_unit.retrieve_by_title"
632 );
633
634 sub orgs_for_title {
635         my( $self, $client, $record_id ) = @_;
636
637         my $vols = $apputils->simple_scalar_request(
638                 "open-ils.cstore",
639                 "open-ils.cstore.direct.asset.call_number.search.atomic",
640                 { record => $record_id, deleted => 'f' });
641
642         my $orgs = { map {$_->owning_lib => 1 } @$vols };
643         return [ keys %$orgs ];
644 }
645
646
647 __PACKAGE__->register_method(
648         method  => "retrieve_copies",
649     authoritative => 1,
650         api_name        => "open-ils.cat.asset.copy_tree.retrieve");
651
652 __PACKAGE__->register_method(
653         method  => "retrieve_copies",
654         api_name        => "open-ils.cat.asset.copy_tree.global.retrieve");
655
656 # user_session may be null/undef
657 sub retrieve_copies {
658
659         my( $self, $client, $user_session, $docid, @org_ids ) = @_;
660
661         if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
662
663         $docid = "$docid";
664
665         warn " $$ retrieving copy tree for orgs @org_ids and doc $docid at " . time() . "\n";
666
667         # grabbing copy trees should be available for everyone..
668         if(!@org_ids and $user_session) {
669                 my $user_obj = 
670                         OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
671                         @org_ids = ($user_obj->home_ou);
672         }
673
674         if( $self->api_name =~ /global/ ) {
675                 warn "performing global copy_tree search for $docid\n";
676                 return _build_volume_list( { record => $docid, deleted => 'f' } );
677
678         } else {
679
680                 my @all_vols;
681                 for my $orgid (@org_ids) {
682                         my $vols = _build_volume_list( 
683                                         { record => $docid, owning_lib => $orgid, deleted => 'f' } );
684                         warn "Volumes built for org $orgid\n";
685                         push( @all_vols, @$vols );
686                 }
687                 
688                 warn " $$ Finished copy_tree at " . time() . "\n";
689                 return \@all_vols;
690         }
691
692         return undef;
693 }
694
695
696 sub _build_volume_list {
697         my $search_hash = shift;
698
699         $search_hash->{deleted} = 'f';
700         my $e = new_editor();
701
702         my $vols = $e->search_asset_call_number($search_hash);
703
704         my @volumes;
705
706         for my $volume (@$vols) {
707
708                 my $copies = $e->search_asset_copy(
709                         { call_number => $volume->id , deleted => 'f' });
710
711                 $copies = [ sort { $a->barcode cmp $b->barcode } @$copies  ];
712
713                 for my $c (@$copies) {
714                         if( $c->status == OILS_COPY_STATUS_CHECKED_OUT ) {
715                                 $c->circulations(
716                                         $e->search_action_circulation(
717                                                 [
718                                                         { target_copy => $c->id },
719                                                         {
720                                                                 order_by => { circ => 'xact_start desc' },
721                                                                 limit => 1
722                                                         }
723                                                 ]
724                                         )
725                                 )
726                         }
727                 }
728
729                 $volume->copies($copies);
730                 push( @volumes, $volume );
731         }
732
733         #$session->disconnect();
734         return \@volumes;
735
736 }
737
738
739 __PACKAGE__->register_method(
740         method  => "fleshed_copy_update",
741         api_name        => "open-ils.cat.asset.copy.fleshed.batch.update",);
742
743 __PACKAGE__->register_method(
744         method  => "fleshed_copy_update",
745         api_name        => "open-ils.cat.asset.copy.fleshed.batch.update.override",);
746
747
748 sub fleshed_copy_update {
749         my( $self, $conn, $auth, $copies, $delete_stats ) = @_;
750         return 1 unless ref $copies;
751         my( $reqr, $evt ) = $U->checkses($auth);
752         return $evt if $evt;
753         my $editor = new_editor(requestor => $reqr, xact => 1);
754         my $override = $self->api_name =~ /override/;
755         $evt = update_fleshed_copies($editor, $override, undef, $copies, $delete_stats);
756         if( $evt ) { 
757                 $logger->info("fleshed copy update failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
758                 $editor->rollback; 
759                 return $evt; 
760         }
761         $editor->commit;
762         $logger->info("fleshed copy update successfully updated ".scalar(@$copies)." copies");
763         return 1;
764 }
765
766
767 __PACKAGE__->register_method(
768         method => 'merge',
769         api_name        => 'open-ils.cat.biblio.records.merge',
770         signature       => q/
771                 Merges a group of records
772                 @param auth The login session key
773                 @param master The id of the record all other records should be merged into
774                 @param records Array of records to be merged into the master record
775                 @return 1 on success, Event on error.
776         /
777 );
778
779 sub merge {
780         my( $self, $conn, $auth, $master, $records ) = @_;
781         my( $reqr, $evt ) = $U->checkses($auth);
782         return $evt if $evt;
783         my $editor = new_editor( requestor => $reqr, xact => 1 );
784         my $v = OpenILS::Application::Cat::Merge::merge_records($editor, $master, $records);
785         return $v if $v;
786         $editor->commit;
787     # tell the client the merge is complete, then merge the holds
788     $conn->respond_complete(1);
789     merge_holds($master, $records);
790         return undef;
791 }
792
793 sub merge_holds {
794     my($master, $records) = @_;
795     return unless $master and @$records;
796     return if @$records == 1 and $master == $$records[0];
797
798     my $e = new_editor(xact=>1);
799     my $holds = $e->search_action_hold_request(
800         {   cancel_time => undef, 
801             fulfillment_time => undef,
802             hold_type => 'T',
803             target => $records
804         },
805         {idlist=>1}
806     );
807
808     for my $hold_id (@$holds) {
809
810         my $hold = $e->retrieve_action_hold_request($hold_id);
811
812         $logger->info("Changing hold ".$hold->id.
813             " target from ".$hold->target." to $master in record merge");
814
815         $hold->target($master);
816         unless($e->update_action_hold_request($hold)) {
817             my $evt = $e->event;
818             $logger->error("Error updating hold ". $evt->textcode .":". $evt->desc .":". $evt->stacktrace); 
819         }
820     }
821
822     $e->commit;
823     return undef;
824 }
825
826
827
828
829 # ---------------------------------------------------------------------------
830 # ---------------------------------------------------------------------------
831
832 # returns true if the given title (id) has no un-deleted
833 # copies attached
834 sub title_is_empty {
835         my( $editor, $rid ) = @_;
836
837         return 0 if $rid == OILS_PRECAT_RECORD;
838
839         my $cnlist = $editor->search_asset_call_number(
840                 { record => $rid, deleted => 'f' }, { idlist => 1 } );
841         return 1 unless @$cnlist;
842
843         for my $cn (@$cnlist) {
844                 my $copylist = $editor->search_asset_copy(
845                         [
846                                 { call_number => $cn, deleted => 'f' }, 
847                                 { limit => 1 },
848                         ], { idlist => 1 });
849                 return 0 if @$copylist; # false if we find any copies
850         }
851
852         return 1;
853 }
854
855
856 __PACKAGE__->register_method(
857         method  => "fleshed_volume_update",
858         api_name        => "open-ils.cat.asset.volume.fleshed.batch.update",);
859
860 __PACKAGE__->register_method(
861         method  => "fleshed_volume_update",
862         api_name        => "open-ils.cat.asset.volume.fleshed.batch.update.override",);
863
864 sub fleshed_volume_update {
865         my( $self, $conn, $auth, $volumes, $delete_stats ) = @_;
866         my( $reqr, $evt ) = $U->checkses($auth);
867         return $evt if $evt;
868
869         my $override = ($self->api_name =~ /override/);
870         my $editor = new_editor( requestor => $reqr, xact => 1 );
871
872         for my $vol (@$volumes) {
873                 $logger->info("vol-update: investigating volume ".$vol->id);
874
875                 $vol->editor($reqr->id);
876                 $vol->edit_date('now');
877
878                 my $copies = $vol->copies;
879                 $vol->clear_copies;
880
881                 $vol->editor($editor->requestor->id);
882                 $vol->edit_date('now');
883
884                 if( $vol->isdeleted ) {
885
886                         $logger->info("vol-update: deleting volume");
887                         my $cs = $editor->search_asset_copy(
888                                 { call_number => $vol->id, deleted => 'f' } );
889                         return OpenILS::Event->new(
890                                 'VOLUME_NOT_EMPTY', payload => $vol->id ) if @$cs;
891
892                         $vol->deleted('t');
893                         return $editor->event unless
894                                 $editor->update_asset_call_number($vol);
895
896                         
897                 } elsif( $vol->isnew ) {
898                         $logger->info("vol-update: creating volume");
899                         $evt = create_volume( $override, $editor, $vol );
900                         return $evt if $evt;
901
902                 } elsif( $vol->ischanged ) {
903                         $logger->info("vol-update: update volume");
904                         $evt = update_volume($vol, $editor);
905                         return $evt if $evt;
906                 }
907
908                 # now update any attached copies
909                 if( $copies and @$copies and !$vol->isdeleted ) {
910                         $_->call_number($vol->id) for @$copies;
911                         $evt = update_fleshed_copies( $editor, $override, $vol, $copies, $delete_stats );
912                         return $evt if $evt;
913                 }
914         }
915
916         $editor->finish;
917         return scalar(@$volumes);
918 }
919
920
921 sub update_volume {
922         my $vol = shift;
923         my $editor = shift;
924         my $evt;
925
926         return $evt if ( $evt = org_cannot_have_vols($editor, $vol->owning_lib) );
927
928         my $vols = $editor->search_asset_call_number( { 
929                         owning_lib      => $vol->owning_lib,
930                         record          => $vol->record,
931                         label                   => $vol->label,
932                         deleted         => 'f'
933                 }
934         );
935
936         # There exists a different volume in the DB with the same properties
937         return OpenILS::Event->new('VOLUME_LABEL_EXISTS', payload => $vol->id)
938                 if grep { $_->id ne $vol->id } @$vols;
939
940         return $editor->event unless $editor->update_asset_call_number($vol);
941         return undef;
942 }
943
944
945
946 sub copy_perm_org {
947         my( $vol, $copy ) = @_;
948         my $org = $vol->owning_lib;
949         if( $vol->id == OILS_PRECAT_CALL_NUMBER ) {
950                 $org = ref($copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
951         }
952         $logger->debug("using copy perm org $org");
953         return $org;
954 }
955
956
957 # this does the actual work
958 sub update_fleshed_copies {
959         my( $editor, $override, $vol, $copies, $delete_stats ) = @_;
960
961         my $evt;
962         my $fetchvol = ($vol) ? 0 : 1;
963
964         my %cache;
965         $cache{$vol->id} = $vol if $vol;
966
967         for my $copy (@$copies) {
968
969                 my $copyid = $copy->id;
970                 $logger->info("vol-update: inspecting copy $copyid");
971
972                 if( !($vol = $cache{$copy->call_number}) ) {
973                         $vol = $cache{$copy->call_number} = 
974                                 $editor->retrieve_asset_call_number($copy->call_number);
975                         return $editor->event unless $vol;
976                 }
977
978                 return $editor->event unless 
979                         $editor->allowed('UPDATE_COPY', copy_perm_org($vol, $copy));
980
981                 $copy->editor($editor->requestor->id);
982                 $copy->edit_date('now');
983
984                 $copy->status( $copy->status->id ) if ref($copy->status);
985                 $copy->location( $copy->location->id ) if ref($copy->location);
986                 $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
987                 
988                 my $sc_entries = $copy->stat_cat_entries;
989                 $copy->clear_stat_cat_entries;
990
991                 if( $copy->isdeleted ) {
992                         $evt = delete_copy($editor, $override, $vol, $copy);
993                         return $evt if $evt;
994
995                 } elsif( $copy->isnew ) {
996                         $evt = create_copy( $editor, $vol, $copy );
997                         return $evt if $evt;
998
999                 } elsif( $copy->ischanged ) {
1000
1001                         $evt = update_copy( $editor, $override, $vol, $copy );
1002                         return $evt if $evt;
1003                 }
1004
1005                 $copy->stat_cat_entries( $sc_entries );
1006                 $evt = update_copy_stat_entries($editor, $copy, $delete_stats);
1007                 return $evt if $evt;
1008         }
1009
1010         $logger->debug("vol-update: done updating copy batch");
1011
1012         return undef;
1013 }
1014
1015 sub fix_copy_price {
1016         my $copy = shift;
1017
1018     if(defined $copy->price) {
1019             my $p = $copy->price || 0;
1020             $p =~ s/\$//og;
1021             $copy->price($p);
1022     }
1023
1024         my $d = $copy->deposit_amount || 0;
1025         $d =~ s/\$//og;
1026         $copy->deposit_amount($d);
1027 }
1028
1029
1030 sub update_copy {
1031         my( $editor, $override, $vol, $copy ) = @_;
1032
1033         my $evt;
1034         my $org = (ref $copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
1035         return $evt if ( $evt = org_cannot_have_vols($editor, $org) );
1036
1037         $logger->info("vol-update: updating copy ".$copy->id);
1038         my $orig_copy = $editor->retrieve_asset_copy($copy->id);
1039         my $orig_vol  = $editor->retrieve_asset_call_number($copy->call_number);
1040
1041         $copy->editor($editor->requestor->id);
1042         $copy->edit_date('now');
1043
1044         $copy->age_protect( $copy->age_protect->id )
1045                 if ref $copy->age_protect;
1046
1047         fix_copy_price($copy);
1048
1049         return $editor->event unless $editor->update_asset_copy($copy);
1050         return remove_empty_objects($editor, $override, $orig_vol);
1051 }
1052
1053
1054 sub remove_empty_objects {
1055         my( $editor, $override, $vol ) = @_; 
1056
1057     my $koe = $U->ou_ancestor_setting_value(
1058         $editor->requestor->ws_ou, 'cat.bib.keep_on_empty', $editor);
1059     my $aoe =  $U->ou_ancestor_setting_value(
1060         $editor->requestor->ws_ou, 'cat.bib.alert_on_empty', $editor);
1061
1062         if( title_is_empty($editor, $vol->record) ) {
1063
1064         # delete this volume if it's not already marked as deleted
1065         unless( $U->is_true($vol->deleted) || $vol->isdeleted ) {
1066             $vol->deleted('t');
1067             $vol->editor($editor->requestor->id);
1068             $vol->edit_date('now');
1069             $editor->update_asset_call_number($vol) or return $editor->event;
1070         }
1071
1072         unless($koe) {
1073             # delete the bib record if the keep-on-empty setting is not set
1074             my $evt = delete_rec($editor, $vol->record);
1075             return $evt if $evt;
1076         }
1077
1078         # return the empty alert if the alert-on-empty setting is set
1079         return OpenILS::Event->new('TITLE_LAST_COPY', payload => $vol->record ) if $aoe;
1080         }
1081
1082         return undef;
1083 }
1084
1085
1086 __PACKAGE__->register_method (
1087         method => 'delete_bib_record',
1088         api_name => 'open-ils.cat.biblio.record_entry.delete');
1089
1090 sub delete_bib_record {
1091     my($self, $conn, $auth, $rec_id) = @_;
1092     my $e = new_editor(xact=>1, authtoken=>$auth);
1093     return $e->die_event unless $e->checkauth;
1094     return $e->die_event unless $e->allowed('DELETE_RECORD', $e->requestor->ws_ou);
1095     my $vols = $e->search_asset_call_number({record=>$rec_id, deleted=>'f'});
1096     return OpenILS::Event->new('RECORD_NOT_EMPTY', payload=>$rec_id) if @$vols;
1097     my $evt = delete_rec($e, $rec_id);
1098     if($evt) { $e->rollback; return $evt; }   
1099     $e->commit;
1100     return 1;
1101 }
1102
1103
1104 # marks a record as deleted
1105 sub delete_rec {
1106    my( $editor, $rec_id ) = @_;
1107
1108    my $rec = $editor->retrieve_biblio_record_entry($rec_id)
1109       or return $editor->event;
1110
1111    return undef if $U->is_true($rec->deleted);
1112    
1113    $rec->deleted('t');
1114    $rec->active('f');
1115    $rec->editor( $editor->requestor->id );
1116    $rec->edit_date('now');
1117    $editor->update_biblio_record_entry($rec) or return $editor->event;
1118
1119    return undef;
1120 }
1121
1122
1123 sub delete_copy {
1124         my( $editor, $override, $vol, $copy ) = @_;
1125
1126    return $editor->event unless 
1127       $editor->allowed('DELETE_COPY',copy_perm_org($vol, $copy));
1128
1129         my $stat = $U->copy_status($copy->status)->id;
1130
1131         unless($override) {
1132                 return OpenILS::Event->new('COPY_DELETE_WARNING', payload => $copy->id )
1133                         if $stat == OILS_COPY_STATUS_CHECKED_OUT or
1134                                 $stat == OILS_COPY_STATUS_IN_TRANSIT or
1135                                 $stat == OILS_COPY_STATUS_ON_HOLDS_SHELF or
1136                                 $stat == OILS_COPY_STATUS_ILL;
1137         }
1138
1139         $logger->info("vol-update: deleting copy ".$copy->id);
1140         $copy->deleted('t');
1141
1142         $copy->editor($editor->requestor->id);
1143         $copy->edit_date('now');
1144         $editor->update_asset_copy($copy) or return $editor->event;
1145
1146         # Delete any open transits for this copy
1147         my $transits = $editor->search_action_transit_copy(
1148                 { target_copy=>$copy->id, dest_recv_time => undef } );
1149
1150         for my $t (@$transits) {
1151                 $editor->delete_action_transit_copy($t)
1152                         or return $editor->event;
1153         }
1154
1155         return remove_empty_objects($editor, $override, $vol);
1156 }
1157
1158
1159 sub create_copy {
1160         my( $editor, $vol, $copy ) = @_;
1161
1162         my $existing = $editor->search_asset_copy(
1163                 { barcode => $copy->barcode, deleted => 'f' } );
1164         
1165         return OpenILS::Event->new('ITEM_BARCODE_EXISTS') if @$existing;
1166
1167    # see if the volume this copy references is marked as deleted
1168    my $evol = $editor->retrieve_asset_call_number($copy->call_number)
1169       or return $editor->event;
1170    return OpenILS::Event->new('VOLUME_DELETED', vol => $evol->id) 
1171       if $U->is_true($evol->deleted);
1172
1173         my $evt;
1174         my $org = (ref $copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
1175         return $evt if ( $evt = org_cannot_have_vols($editor, $org) );
1176
1177         $copy->clear_id;
1178         $copy->creator($editor->requestor->id);
1179         $copy->create_date('now');
1180         fix_copy_price($copy);
1181
1182         $editor->create_asset_copy($copy) or return $editor->event;
1183         return undef;
1184 }
1185
1186 # if 'delete_stats' is true, the copy->stat_cat_entries data is 
1187 # treated as the authoritative list for the copy. existing entries
1188 # that are not in said list will be deleted from the DB
1189 sub update_copy_stat_entries {
1190         my( $editor, $copy, $delete_stats ) = @_;
1191
1192         return undef if $copy->isdeleted;
1193         return undef unless $copy->ischanged or $copy->isnew;
1194
1195         my $evt;
1196         my $entries = $copy->stat_cat_entries;
1197
1198         if( $delete_stats ) {
1199                 $entries = ($entries and @$entries) ? $entries : [];
1200         } else {
1201                 return undef unless ($entries and @$entries);
1202         }
1203
1204         my $maps = $editor->search_asset_stat_cat_entry_copy_map({owning_copy=>$copy->id});
1205
1206         if(!$copy->isnew) {
1207                 # if there is no stat cat entry on the copy who's id matches the
1208                 # current map's id, remove the map from the database
1209                 for my $map (@$maps) {
1210                         if(! grep { $_->id == $map->stat_cat_entry } @$entries ) {
1211
1212                                 $logger->info("copy update found stale ".
1213                                         "stat cat entry map ".$map->id. " on copy ".$copy->id);
1214
1215                                 $editor->delete_asset_stat_cat_entry_copy_map($map)
1216                                         or return $editor->event;
1217                         }
1218                 }
1219         }
1220
1221         # go through the stat cat update/create process
1222         for my $entry (@$entries) { 
1223                 next unless $entry;
1224
1225                 # if this link already exists in the DB, don't attempt to re-create it
1226                 next if( grep{$_->stat_cat_entry == $entry->id} @$maps );
1227         
1228                 my $new_map = Fieldmapper::asset::stat_cat_entry_copy_map->new();
1229
1230                 my $sc = ref($entry->stat_cat) ? $entry->stat_cat->id : $entry->stat_cat;
1231                 
1232                 $new_map->stat_cat( $sc );
1233                 $new_map->stat_cat_entry( $entry->id );
1234                 $new_map->owning_copy( $copy->id );
1235
1236                 $editor->create_asset_stat_cat_entry_copy_map($new_map)
1237                         or return $editor->event;
1238
1239                 $logger->info("copy update created new stat cat entry map ".$editor->data);
1240         }
1241
1242         return undef;
1243 }
1244
1245
1246 sub create_volume {
1247         my( $override, $editor, $vol ) = @_;
1248         my $evt;
1249
1250         return $evt if ( $evt = org_cannot_have_vols($editor, $vol->owning_lib) );
1251
1252    # see if the record this volume references is marked as deleted
1253    my $rec = $editor->retrieve_biblio_record_entry($vol->record)
1254       or return $editor->event;
1255    return OpenILS::Event->new('BIB_RECORD_DELETED', rec => $rec->id) 
1256       if $U->is_true($rec->deleted);
1257
1258         # first lets see if there are any collisions
1259         my $vols = $editor->search_asset_call_number( { 
1260                         owning_lib      => $vol->owning_lib,
1261                         record          => $vol->record,
1262                         label                   => $vol->label,
1263                         deleted         => 'f'
1264                 }
1265         );
1266
1267         my $label = undef;
1268         if(@$vols) {
1269       # we've found an exising volume
1270                 if($override) { 
1271                         $label = $vol->label;
1272                 } else {
1273                         return OpenILS::Event->new(
1274                                 'VOLUME_LABEL_EXISTS', payload => $vol->id);
1275                 }
1276         }
1277
1278         # create a temp label so we can create the new volume, 
1279    # then de-dup it with the existing volume
1280         $vol->label( "__SYSTEM_TMP_$$".time) if $label;
1281
1282         $vol->creator($editor->requestor->id);
1283         $vol->create_date('now');
1284         $vol->editor($editor->requestor->id);
1285         $vol->edit_date('now');
1286         $vol->clear_id;
1287
1288         $editor->create_asset_call_number($vol) or return $editor->event;
1289
1290         if($label) {
1291                 # now restore the label and merge into the existing record
1292                 $vol->label($label);
1293                 (undef, $evt) = 
1294                         OpenILS::Application::Cat::Merge::merge_volumes($editor, [$vol], $$vols[0]);
1295                 return $evt if $evt;
1296         }
1297
1298         return undef;
1299 }
1300
1301
1302 __PACKAGE__->register_method (
1303         method => 'batch_volume_transfer',
1304         api_name => 'open-ils.cat.asset.volume.batch.transfer',
1305 );
1306
1307 __PACKAGE__->register_method (
1308         method => 'batch_volume_transfer',
1309         api_name => 'open-ils.cat.asset.volume.batch.transfer.override',
1310 );
1311
1312
1313 sub batch_volume_transfer {
1314         my( $self, $conn, $auth, $args ) = @_;
1315
1316         my $evt;
1317         my $rec         = $$args{docid};
1318         my $o_lib       = $$args{lib};
1319         my $vol_ids = $$args{volumes};
1320
1321         my $override = 1 if $self->api_name =~ /override/;
1322
1323         $logger->info("merge: transferring volumes to lib=$o_lib and record=$rec");
1324
1325         my $e = new_editor(authtoken => $auth, xact =>1);
1326         return $e->event unless $e->checkauth;
1327         return $e->event unless $e->allowed('UPDATE_VOLUME', $o_lib);
1328
1329         my $dorg = $e->retrieve_actor_org_unit($o_lib)
1330                 or return $e->event;
1331
1332         my $ou_type = $e->retrieve_actor_org_unit_type($dorg->ou_type)
1333                 or return $e->event;
1334
1335         return $evt if ( $evt = org_cannot_have_vols($e, $o_lib) );
1336
1337         my $vols = $e->batch_retrieve_asset_call_number($vol_ids);
1338         my @seen;
1339
1340    my @rec_ids;
1341
1342         for my $vol (@$vols) {
1343
1344                 # if we've already looked at this volume, go to the next
1345                 next if !$vol or grep { $vol->id == $_ } @seen;
1346
1347                 # grab all of the volumes in the list that have 
1348                 # the same label so they can be merged
1349                 my @all = grep { $_->label eq $vol->label } @$vols;
1350
1351                 # take note of the fact that we've looked at this set of volumes
1352                 push( @seen, $_->id ) for @all;
1353       push( @rec_ids, $_->record ) for @all;
1354
1355                 # for each volume, see if there are any copies that have a 
1356                 # remote circ_lib (circ_lib != vol->owning_lib and != $o_lib ).  
1357                 # if so, warn them
1358                 unless( $override ) {
1359                         for my $v (@all) {
1360
1361                                 $logger->debug("merge: searching for copies with remote circ_lib for volume ".$v->id);
1362                                 my $args = { 
1363                                         call_number     => $v->id, 
1364                                         circ_lib                => { "not in" => [ $o_lib, $v->owning_lib ] },
1365                                         deleted         => 'f'
1366                                 };
1367
1368                                 my $copies = $e->search_asset_copy($args, {idlist=>1});
1369
1370                                 # if the copy's circ_lib matches the destination lib,
1371                                 # that's ok too
1372                                 return OpenILS::Event->new('COPY_REMOTE_CIRC_LIB') if @$copies;
1373                         }
1374                 }
1375
1376                 # see if there is a volume at the destination lib that 
1377                 # already has the requested label
1378                 my $existing_vol = $e->search_asset_call_number(
1379                         {
1380                                 label                   => $vol->label, 
1381                                 record          =>$rec, 
1382                                 owning_lib      =>$o_lib,
1383                                 deleted         => 'f'
1384                         }
1385                 )->[0];
1386
1387                 if( $existing_vol ) {
1388
1389                         if( grep { $_->id == $existing_vol->id } @all ) {
1390                                 # this volume is already accounted for in our list of volumes to merge
1391                                 $existing_vol = undef;
1392
1393                         } else {
1394                                 # this volume exists on the destination record/owning_lib and must
1395                                 # be used as the destination for merging
1396                                 $logger->debug("merge: volume already exists at destination record: ".
1397                                         $existing_vol->id.' : '.$existing_vol->label) if $existing_vol;
1398                         }
1399                 } 
1400
1401                 if( @all > 1 || $existing_vol ) {
1402                         $logger->info("merge: found collisions in volume transfer");
1403                         my @args = ($e, \@all);
1404                         @args = ($e, \@all, $existing_vol) if $existing_vol;
1405                         ($vol, $evt) = OpenILS::Application::Cat::Merge::merge_volumes(@args);
1406                         return $evt if $evt;
1407                 } 
1408                 
1409                 if( !$existing_vol ) {
1410
1411                         $vol->owning_lib($o_lib);
1412                         $vol->record($rec);
1413                         $vol->editor($e->requestor->id);
1414                         $vol->edit_date('now');
1415         
1416                         $logger->info("merge: updating volume ".$vol->id);
1417                         $e->update_asset_call_number($vol) or return $e->event;
1418
1419                 } else {
1420                         $logger->info("merge: bypassing volume update because existing volume used as target");
1421                 }
1422
1423                 # regardless of what volume was used as the destination, 
1424                 # update any copies that have moved over to the new lib
1425                 my $copies = $e->search_asset_copy({call_number=>$vol->id, deleted => 'f'});
1426
1427                 # update circ lib on the copies - make this a method flag?
1428                 for my $copy (@$copies) {
1429                         next if $copy->circ_lib == $o_lib;
1430                         $logger->info("merge: transfer moving circ lib on copy ".$copy->id);
1431                         $copy->circ_lib($o_lib);
1432                         $copy->editor($e->requestor->id);
1433                         $copy->edit_date('now');
1434                         $e->update_asset_copy($copy) or return $e->event;
1435                 }
1436
1437                 # Now see if any empty records need to be deleted after all of this
1438
1439       for(@rec_ids) {
1440          $logger->debug("merge: seeing if we should delete record $_...");
1441          $evt = delete_rec($e, $_) if title_is_empty($e, $_);
1442                         return $evt if $evt;
1443       }
1444
1445                 #for(@all) {
1446                 #       $evt = remove_empty_objects($e, $override, $_);
1447                 #}
1448         }
1449
1450         $logger->info("merge: transfer succeeded");
1451         $e->commit;
1452         return 1;
1453 }
1454
1455
1456
1457 sub org_cannot_have_vols {
1458         my $e = shift;
1459         my $org_id = shift;
1460
1461         my $org = $e->retrieve_actor_org_unit($org_id)
1462                 or return $e->event;
1463
1464         my $ou_type = $e->retrieve_actor_org_unit_type($org->ou_type)
1465                 or return $e->event;
1466
1467         return OpenILS::Event->new('ORG_CANNOT_HAVE_VOLS')
1468                 unless $U->is_true($ou_type->can_have_vols);
1469
1470         return 0;
1471 }
1472
1473
1474
1475
1476 __PACKAGE__->register_method(
1477         api_name => 'open-ils.cat.call_number.find_or_create',
1478         method => 'find_or_create_volume',
1479 );
1480
1481 sub find_or_create_volume {
1482         my( $self, $conn, $auth, $label, $record_id, $org_id ) = @_;
1483         my $e = new_editor(authtoken=>$auth, xact=>1);
1484         return $e->die_event unless $e->checkauth;
1485
1486     my $vol;
1487
1488     if($record_id == OILS_PRECAT_RECORD) {
1489
1490         $vol = $e->retrieve_asset_call_number(OILS_PRECAT_CALL_NUMBER)
1491             or return $e->die_event;
1492
1493     } else {
1494         
1495             $vol = $e->search_asset_call_number(
1496                     {label => $label, record => $record_id, owning_lib => $org_id, deleted => 'f'}, 
1497                     {idlist=>1}
1498             )->[0];
1499     }
1500
1501         # If the volume exists, return the ID
1502         if( $vol ) { $e->rollback; return $vol; }
1503
1504         # -----------------------------------------------------------------
1505         # Otherwise, create a new volume with the given attributes
1506         # -----------------------------------------------------------------
1507
1508         return $e->die_event unless $e->allowed('UPDATE_VOLUME', $org_id);
1509
1510         $vol = Fieldmapper::asset::call_number->new;
1511         $vol->owning_lib($org_id);
1512         $vol->label($label);
1513         $vol->record($record_id);
1514
1515    my $evt = create_volume( 0, $e, $vol );
1516    return $evt if $evt;
1517
1518         $e->commit;
1519         return $vol->id;
1520 }
1521
1522
1523
1524 1;