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