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