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