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