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