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