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