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