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);
11 use OpenILS::Utils::Fieldmapper;
13 use OpenILS::Const qw/:const/;
16 use Unicode::Normalize;
18 use OpenILS::Utils::FlatXML;
19 use OpenILS::Utils::CStoreEditor q/:funcs/;
20 use OpenILS::Utils::Editor;
22 use OpenSRF::Utils::SettingsClient;
23 use OpenSRF::Utils::Logger qw($logger);
24 use OpenSRF::AppSession;
26 my $apputils = "OpenILS::Application::AppUtils";
28 my $utils = "OpenILS::Application::Cat::Utils";
29 my $U = "OpenILS::Application::AppUtils";
37 my $form = shift || "";
45 $stuff =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
49 __PACKAGE__->register_method(
50 method => "retrieve_marc_template",
51 api_name => "open-ils.cat.biblio.marc_template.retrieve",
53 Returns a MARC 'record tree' based on a set of pre-defined templates.
54 Templates include : book
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};
64 __PACKAGE__->register_method(
65 method => 'fetch_marc_template_types',
66 api_name => 'open-ils.cat.marc_template.types.retrieve'
69 my $marc_template_files;
71 sub fetch_marc_template_types {
72 my( $self, $conn ) = @_;
73 __load_marc_templates();
74 return [ keys %$marc_template_files ];
77 sub __load_marc_templates {
78 return if $marc_template_files;
79 if(!$conf) { $conf = OpenSRF::Utils::SettingsClient->new; }
81 $marc_template_files = $conf->config_value(
82 "apps", "open-ils.cat","app_settings", "marctemplates" );
84 $logger->info("Loaded marc templates: " . Dumper($marc_template_files));
87 sub _load_marc_template {
90 __load_marc_templates();
92 my $template = $$marc_template_files{$type};
93 open( F, $template ) or
94 throw OpenSRF::EX::ERROR ("Unable to open MARC template file: $template : $@");
98 my $xml = join('', @xml);
100 return XML::LibXML->new->parse_string($xml)->documentElement->toString;
104 sub bib_source_from_name {
106 $logger->debug("searching for bib source: $name");
110 my ($s) = grep { lc($_->source) eq lc($name) } @$__bib_sources;
117 __PACKAGE__->register_method(
118 method => 'fetch_bib_sources',
119 api_name => 'open-ils.cat.bib_sources.retrieve.all');
121 sub fetch_bib_sources {
122 $__bib_sources = new_editor()->retrieve_all_config_bib_source()
123 unless $__bib_sources;
124 return $__bib_sources;
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/);
134 __PACKAGE__->register_method(
135 method => "create_record_xml",
136 api_name => "open-ils.cat.biblio.record.xml.create",
138 Inserts a new biblio with the given XML
142 sub create_record_xml {
143 my( $self, $client, $login, $xml, $source ) = @_;
145 my $override = 1 if $self->api_name =~ /override/;
147 my( $user_obj, $evt ) = $U->checksesperm($login, 'CREATE_MARC');
150 $logger->activity("user ".$user_obj->id." creating new MARC record");
152 my $meth = $self->method_lookup("open-ils.cat.biblio.record.xml.import");
154 $meth = $self->method_lookup(
155 "open-ils.cat.biblio.record.xml.import.override") if $override;
157 my ($s) = $meth->run($login, $xml, $source);
163 __PACKAGE__->register_method(
164 method => "biblio_record_replace_marc",
165 api_name => "open-ils.cat.biblio.record.xml.update",
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
175 __PACKAGE__->register_method(
176 method => 'biblio_record_replace_marc',
177 api_name => 'open-ils.cat.biblio.record.marc.replace',
179 @param auth The authtoken
180 @param recid The record whose MARC we're replacing
181 @param newxml The new xml to use
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/
191 sub biblio_record_replace_marc {
192 my( $self, $conn, $auth, $recid, $newxml, $source ) = @_;
194 warn "Updating MARC with xml\n$newxml\n";
196 my $e = OpenILS::Utils::Editor->new(authtoken=>$auth, xact=>1);
198 return $e->die_event unless $e->checkauth;
199 return $e->die_event unless $e->allowed('CREATE_MARC');
201 my $rec = $e->retrieve_biblio_record_entry($recid)
202 or return $e->die_event;
204 my $fixtcn = 1 if $self->api_name =~ /replace/o;
206 # See if there is a different record in the database that has our TCN value
207 # If we're not updating the TCN, all we care about it the marcdoc
208 my $override = $self->api_name =~ /override/;
211 my $storage = OpenSRF::AppSession->create('open-ils.storage');
213 # XXX should .update even bother with the tcn_info if it's not going to replace it?
214 # there is the potential for returning a TCN_EXISTS event, even though no replacement happens
216 my( $tcn, $tsource, $marcdoc, $evt) =
217 _find_tcn_info($e->session, $newxml, $override, $recid);
222 $rec->tcn_value($tcn);
223 $rec->tcn_source($tsource);
226 $rec->source(bib_source_from_name($source)) if $source;
227 $rec->editor($e->requestor->id);
228 $rec->edit_date('now');
229 $rec->marc( entityize( $marcdoc->documentElement->toString ) );
231 $logger->activity("user ".$e->requestor->id." replacing MARC for record $recid");
233 $e->update_biblio_record_entry($rec) or return $e->event;
236 $conn->respond_complete($rec);
240 'open-ils.ingest.full.biblio.record', $recid );
248 __PACKAGE__->register_method(
249 method => "biblio_record_xml_import",
250 api_name => "open-ils.cat.biblio.record.xml.import.override",
251 signature => q/@see open-ils.cat.biblio.record.xml.import/);
253 __PACKAGE__->register_method(
254 method => "biblio_record_xml_import",
255 api_name => "open-ils.cat.biblio.record.xml.import",
256 notes => <<" NOTES");
257 Takes a marcxml record and imports the record into the database. In this
258 case, the marcxml record is assumed to be a complete record (i.e. valid
259 MARC). The title control number is taken from (whichever comes first)
260 tags 001, 039[ab], 020a, 022a, 010, 035a and whichever does not already exist
262 user_session must have IMPORT_MARC permissions
266 sub biblio_record_xml_import {
267 my( $self, $client, $authtoken, $xml, $source, $auto_tcn) = @_;
269 my $override = 1 if $self->api_name =~ /override/;
271 my( $tcn, $tcn_source, $marcdoc );
272 my( $requestor, $evt ) = $U->checksesperm($authtoken, 'IMPORT_MARC');
275 my $session = $apputils->start_db_session();
278 # auto_tcn forces a blank TCN value so the DB will have to generate one for us
279 $marcdoc = __make_marc_doc($xml);
281 ( $tcn, $tcn_source, $marcdoc, $evt ) = _find_tcn_info($session, $xml, $override);
285 $logger->info("user ".$requestor->id.
286 " creating new biblio entry with tcn=$tcn and tcn_source $tcn_source");
288 my $record = Fieldmapper::biblio::record_entry->new;
290 $record->source(bib_source_from_name($source)) if $source;
291 $record->tcn_source($tcn_source);
292 $record->tcn_value($tcn);
293 $record->creator($requestor->id);
294 $record->editor($requestor->id);
295 $record->create_date('now');
296 $record->edit_date('now');
297 $record->marc( entityize( $marcdoc->documentElement->toString ) );
299 my $id = $session->request(
300 "open-ils.storage.direct.biblio.record_entry.create", $record )->gather(1);
302 return $U->DB_UPDATE_FAILED($record) unless $id;
305 $logger->info("marc create/import created new record $id");
307 $apputils->commit_db_session($session);
309 $logger->debug("Sending record off to be wormized");
311 $client->respond_complete($record);
315 'open-ils.ingest.full.biblio.record', $id );
320 sub __make_marc_doc {
322 my $marcxml = XML::LibXML->new->parse_string( $xml );
323 $marcxml->documentElement->setNamespace(
324 "http://www.loc.gov/MARC21/slim", "marc", 1 );
332 my $override = shift;
333 my $existing_rec = shift || 0;
336 my $marcxml = __make_marc_doc($xml);
337 # my $marcxml = XML::LibXML->new->parse_string( $xml );
338 # $marcxml->documentElement->setNamespace(
339 # "http://www.loc.gov/MARC21/slim", "marc", 1 );
341 my $xpath = '//marc:controlfield[@tag="001"]';
342 my $tcn = $marcxml->documentElement->findvalue($xpath);
343 $logger->info("biblio import located 001 (tcn) value of $tcn");
345 $xpath = '//marc:controlfield[@tag="003"]';
346 my $tcn_source = $marcxml->documentElement->findvalue($xpath) || "System Local";
348 if(my $rec = _tcn_exists($session, $tcn, $tcn_source, $existing_rec) ) {
351 $tcn = find_free_tcn( $marcxml, $session, $existing_rec );
353 # if we're overriding, try to find a different TCN to use
356 # XXX Create ALLOW_ALT_TCN permission check support
358 $logger->info("tcn value $tcn already exists, attempting to override");
366 'OPEN_TCN_NOT_FOUND',
367 payload => $marcxml->toString())
373 $logger->warn("tcn value $origtcn already exists in import/create");
375 # otherwise, return event
381 'TCN_EXISTS', payload => {
391 return ($tcn, $tcn_source, $marcxml);
398 my $existing_rec = shift;
402 my $xpath = '//marc:datafield[@tag="039"]/subfield[@code="a"]';
403 my ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
404 $xpath = '//marc:datafield[@tag="039"]/subfield[@code="b"]';
405 my $tcn_source = $marcxml->documentElement->findvalue($xpath) || "System Local";
407 if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {
415 $xpath = '//marc:datafield[@tag="020"]/subfield[@code="a"]';
416 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
417 $tcn_source = "ISBN";
418 if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
422 $xpath = '//marc:datafield[@tag="022"]/subfield[@code="a"]';
423 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
424 $tcn_source = "ISSN";
425 if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
429 $xpath = '//marc:datafield[@tag="010"]';
430 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
431 $tcn_source = "LCCN";
432 if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
436 $xpath = '//marc:datafield[@tag="035"]/subfield[@code="a"]';
437 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
438 $tcn_source = "System Legacy";
439 if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
442 $marcxml->documentElement->removeChild(
443 $marcxml->documentElement->findnodes( '//datafield[@tag="035"]' )
448 return undef unless $tcn;
451 my $df = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'datafield');
452 $df->setAttribute( tag => '039' );
453 $df->setAttribute( ind1 => ' ' );
454 $df->setAttribute( ind2 => ' ' );
455 $marcxml->documentElement->appendChild( $df );
457 my $sfa = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'subfield');
458 $sfa->setAttribute( code => 'a' );
459 $sfa->appendChild( $marcxml->createTextNode( $tcn ) );
460 $df->appendChild( $sfa );
462 my $sfb = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'subfield');
463 $sfb->setAttribute( code => 'b' );
464 $sfb->appendChild( $marcxml->createTextNode( $tcn_source ) );
465 $df->appendChild( $sfb );
477 my $existing_rec = shift || 0;
479 if(!$tcn) {return 0;}
481 $logger->debug("tcn_exists search for tcn $tcn and source $source and id $existing_rec");
483 # XXX why does the source matter?
484 # my $req = $session->request(
485 # { tcn_value => $tcn, tcn_source => $source, deleted => 'f' } );
487 my $req = $session->request(
488 "open-ils.storage.id_list.biblio.record_entry.search_where.atomic",
489 { tcn_value => $tcn, deleted => 'f', id => {'!=' => $existing_rec} } );
491 my $recs = $req->gather(1);
493 if($recs and $recs->[0]) {
494 $logger->debug("_tcn_exists is true for tcn : $tcn ($source)");
498 $logger->debug("_tcn_exists is false for tcn : $tcn ($source)");
503 __PACKAGE__->register_method(
504 method => "biblio_record_record_metadata",
505 api_name => "open-ils.cat.biblio.record.metadata.retrieve",
506 argc => 1, #(session_id, biblio_tree )
507 notes => "Walks the tree and commits any changed nodes " .
508 "adds any new nodes, and deletes any deleted nodes",
511 sub biblio_record_record_metadata {
512 my( $self, $client, $authtoken, $ids ) = @_;
514 return [] unless $ids and @$ids;
516 my $editor = new_editor(authtoken => $authtoken);
517 return $editor->event unless $editor->checkauth;
518 return $editor->event unless $editor->allowed('VIEW_USER');
523 return $editor->event unless
524 my $rec = $editor->retrieve_biblio_record_entry($_);
525 $rec->creator($editor->retrieve_actor_user($rec->creator));
526 $rec->editor($editor->retrieve_actor_user($rec->editor));
527 $rec->clear_marc; # slim the record down
528 push( @results, $rec );
536 __PACKAGE__->register_method(
537 method => "biblio_record_marc_cn",
538 api_name => "open-ils.cat.biblio.record.marc_cn.retrieve",
539 argc => 1, #(bib id )
542 sub biblio_record_marc_cn {
543 my( $self, $client, $id ) = @_;
545 my $session = OpenSRF::AppSession->create("open-ils.cstore");
547 ->request("open-ils.cstore.direct.biblio.record_entry.retrieve", $id )
551 my $doc = XML::LibXML->new->parse_string($marc);
552 $doc->documentElement->setNamespace( "http://www.loc.gov/MARC21/slim", "marc", 1 );
555 for my $tag ( qw/050 055 060 070 080 082 086 088 090 092 096 098 099/ ) {
556 my @node = $doc->findnodes("//marc:datafield[\@tag='$tag']");
558 my $cn = $x->findvalue("marc:subfield[\@code='a' or \@code='b']");
559 push @res, {$tag => $cn} if ($cn);
566 sub _get_id_by_userid {
571 my $session = OpenSRF::AppSession->create( "open-ils.cstore" );
572 my $request = $session->request(
573 "open-ils.cstore.direct.actor.user.search.atomic", { usrname => \@users } );
575 $request->wait_complete;
576 my $response = $request->recv();
577 if(!$request->complete) {
578 throw OpenSRF::EX::ERROR ("no response from cstore on user retrieve");
581 if(UNIVERSAL::isa( $response, "Error")){
582 throw $response ($response);
585 for my $u (@{$response->content}) {
591 $session->disconnect;
598 # commits metadata objects to the db
599 sub _update_record_metadata {
601 my ($session, @docs ) = @_;
603 for my $doc (@docs) {
605 my $user_obj = $doc->{user};
606 my $docid = $doc->{docid};
608 warn "Updating metata for doc $docid\n";
610 my $request = $session->request(
611 "open-ils.storage.direct.biblio.record_entry.retrieve", $docid );
612 my $record = $request->gather(1);
614 warn "retrieved record\n";
615 my ($id) = _get_id_by_userid($user_obj->usrname);
617 warn "got $id from _get_id_by_userid\n";
618 $record->editor($id);
620 warn "Grabbed the record, updating and moving on\n";
622 $request = $session->request(
623 "open-ils.storage.direct.biblio.record_entry.update", $record );
627 warn "committing metarecord update\n";
634 __PACKAGE__->register_method(
635 method => "orgs_for_title",
636 api_name => "open-ils.cat.actor.org_unit.retrieve_by_title"
640 my( $self, $client, $record_id ) = @_;
642 my $vols = $apputils->simple_scalar_request(
644 "open-ils.cstore.direct.asset.call_number.search.atomic",
645 { record => $record_id, deleted => 'f' });
647 my $orgs = { map {$_->owning_lib => 1 } @$vols };
648 return [ keys %$orgs ];
652 __PACKAGE__->register_method(
653 method => "retrieve_copies",
654 api_name => "open-ils.cat.asset.copy_tree.retrieve");
656 __PACKAGE__->register_method(
657 method => "retrieve_copies",
658 api_name => "open-ils.cat.asset.copy_tree.global.retrieve");
660 # user_session may be null/undef
661 sub retrieve_copies {
663 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
665 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
669 warn " $$ retrieving copy tree for orgs @org_ids and doc $docid at " . time() . "\n";
671 # grabbing copy trees should be available for everyone..
672 if(!@org_ids and $user_session) {
674 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
675 @org_ids = ($user_obj->home_ou);
678 if( $self->api_name =~ /global/ ) {
679 warn "performing global copy_tree search for $docid\n";
680 return _build_volume_list( { record => $docid, deleted => 'f' } );
685 for my $orgid (@org_ids) {
686 my $vols = _build_volume_list(
687 { record => $docid, owning_lib => $orgid, deleted => 'f' } );
688 warn "Volumes built for org $orgid\n";
689 push( @all_vols, @$vols );
692 warn " $$ Finished copy_tree at " . time() . "\n";
700 sub _build_volume_list {
701 my $search_hash = shift;
703 $search_hash->{deleted} = 'f';
704 my $e = new_editor();
706 my $vols = $e->search_asset_call_number($search_hash);
710 for my $volume (@$vols) {
712 my $copies = $e->search_asset_copy(
713 { call_number => $volume->id , deleted => 'f' });
715 $copies = [ sort { $a->barcode cmp $b->barcode } @$copies ];
717 for my $c (@$copies) {
718 if( $c->status == OILS_COPY_STATUS_CHECKED_OUT ) {
720 $e->search_action_circulation(
722 { target_copy => $c->id },
724 order_by => { circ => 'xact_start desc' },
733 $volume->copies($copies);
734 push( @volumes, $volume );
737 #$session->disconnect();
743 __PACKAGE__->register_method(
744 method => "fleshed_copy_update",
745 api_name => "open-ils.cat.asset.copy.fleshed.batch.update",);
747 __PACKAGE__->register_method(
748 method => "fleshed_copy_update",
749 api_name => "open-ils.cat.asset.copy.fleshed.batch.update.override",);
752 sub fleshed_copy_update {
753 my( $self, $conn, $auth, $copies, $delete_stats ) = @_;
754 return 1 unless ref $copies;
755 my( $reqr, $evt ) = $U->checkses($auth);
757 my $editor = new_editor(requestor => $reqr, xact => 1);
758 my $override = $self->api_name =~ /override/;
759 $evt = update_fleshed_copies($editor, $override, undef, $copies, $delete_stats);
761 $logger->info("fleshed copy update failed with event: ".JSON->perl2JSON($evt));
766 $logger->info("fleshed copy update successfully updated ".scalar(@$copies)." copies");
771 __PACKAGE__->register_method(
773 api_name => 'open-ils.cat.biblio.records.merge',
775 Merges a group of records
776 @param auth The login session key
777 @param master The id of the record all other r
778 ecords should be merged into
779 @param records Array of records to be merged into the master record
780 @return 1 on success, Event on error.
785 my( $self, $conn, $auth, $master, $records ) = @_;
786 my( $reqr, $evt ) = $U->checkses($auth);
788 my $editor = new_editor( requestor => $reqr, xact => 1 );
789 my $v = OpenILS::Application::Cat::Merge::merge_records($editor, $master, $records);
798 # ---------------------------------------------------------------------------
799 # ---------------------------------------------------------------------------
801 # returns true if the given title (id) has no un-deleted
804 my( $editor, $rid ) = @_;
806 return 0 if $rid == OILS_PRECAT_RECORD;
808 my $cnlist = $editor->search_asset_call_number(
809 { record => $rid, deleted => 'f' }, { idlist => 1 } );
810 return 1 unless @$cnlist;
812 for my $cn (@$cnlist) {
813 my $copylist = $editor->search_asset_copy(
815 { call_number => $cn, deleted => 'f' },
818 return 0 if @$copylist; # false if we find any copies
825 __PACKAGE__->register_method(
826 method => "fleshed_volume_update",
827 api_name => "open-ils.cat.asset.volume.fleshed.batch.update",);
829 __PACKAGE__->register_method(
830 method => "fleshed_volume_update",
831 api_name => "open-ils.cat.asset.volume.fleshed.batch.update.override",);
833 sub fleshed_volume_update {
834 my( $self, $conn, $auth, $volumes, $delete_stats ) = @_;
835 my( $reqr, $evt ) = $U->checkses($auth);
838 my $override = ($self->api_name =~ /override/);
839 my $editor = new_editor( requestor => $reqr, xact => 1 );
841 for my $vol (@$volumes) {
842 $logger->info("vol-update: investigating volume ".$vol->id);
844 $vol->editor($reqr->id);
845 $vol->edit_date('now');
847 my $copies = $vol->copies;
850 $vol->editor($editor->requestor->id);
851 $vol->edit_date('now');
853 if( $vol->isdeleted ) {
855 $logger->info("vol-update: deleting volume");
856 my $cs = $editor->search_asset_copy(
857 { call_number => $vol->id, deleted => 'f' } );
858 return OpenILS::Event->new(
859 'VOLUME_NOT_EMPTY', payload => $vol->id ) if @$cs;
862 return $editor->event unless
863 $editor->update_asset_call_number($vol);
866 } elsif( $vol->isnew ) {
867 $logger->info("vol-update: creating volume");
868 $evt = create_volume( $override, $editor, $vol );
871 } elsif( $vol->ischanged ) {
872 $logger->info("vol-update: update volume");
873 $evt = update_volume($vol, $editor);
877 # now update any attached copies
878 if( @$copies and !$vol->isdeleted ) {
879 $_->call_number($vol->id) for @$copies;
880 $evt = update_fleshed_copies( $editor, $override, $vol, $copies, $delete_stats );
886 return scalar(@$volumes);
895 return $evt if ( $evt = org_cannot_have_vols($editor, $vol->owning_lib) );
897 my $vols = $editor->search_asset_call_number( {
898 owning_lib => $vol->owning_lib,
899 record => $vol->record,
900 label => $vol->label,
905 # There exists a different volume in the DB with the same properties
906 return OpenILS::Event->new('VOLUME_LABEL_EXISTS', payload => $vol->id)
907 if grep { $_->id ne $vol->id } @$vols;
909 return $editor->event unless $editor->update_asset_call_number($vol);
916 my( $vol, $copy ) = @_;
917 my $org = $vol->owning_lib;
918 if( $vol->id == OILS_PRECAT_CALL_NUMBER ) {
919 $org = ref($copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
921 $logger->debug("using copy perm org $org");
926 # this does the actual work
927 sub update_fleshed_copies {
928 my( $editor, $override, $vol, $copies, $delete_stats ) = @_;
931 my $fetchvol = ($vol) ? 0 : 1;
934 $cache{$vol->id} = $vol if $vol;
936 for my $copy (@$copies) {
938 my $copyid = $copy->id;
939 $logger->info("vol-update: inspecting copy $copyid");
941 if( !($vol = $cache{$copy->call_number}) ) {
942 $vol = $cache{$copy->call_number} =
943 $editor->retrieve_asset_call_number($copy->call_number);
944 return $editor->event unless $vol;
947 return $editor->event unless
948 $editor->allowed('UPDATE_COPY', copy_perm_org($vol, $copy));
950 $copy->editor($editor->requestor->id);
951 $copy->edit_date('now');
953 $copy->status( $copy->status->id ) if ref($copy->status);
954 $copy->location( $copy->location->id ) if ref($copy->location);
955 $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
957 my $sc_entries = $copy->stat_cat_entries;
958 $copy->clear_stat_cat_entries;
960 if( $copy->isdeleted ) {
961 $evt = delete_copy($editor, $override, $vol, $copy);
964 } elsif( $copy->isnew ) {
965 $evt = create_copy( $editor, $vol, $copy );
968 } elsif( $copy->ischanged ) {
970 $evt = update_copy( $editor, $override, $vol, $copy );
974 $copy->stat_cat_entries( $sc_entries );
975 $evt = update_copy_stat_entries($editor, $copy, $delete_stats);
979 $logger->debug("vol-update: done updating copy batch");
986 my $p = $copy->price || 0;
990 my $d = $copy->deposit_amount || 0;
992 $copy->deposit_amount($d);
997 my( $editor, $override, $vol, $copy ) = @_;
1000 my $org = (ref $copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
1001 return $evt if ( $evt = org_cannot_have_vols($editor, $org) );
1003 $logger->info("vol-update: updating copy ".$copy->id);
1004 my $orig_copy = $editor->retrieve_asset_copy($copy->id);
1005 my $orig_vol = $editor->retrieve_asset_call_number($copy->call_number);
1007 $copy->editor($editor->requestor->id);
1008 $copy->edit_date('now');
1010 $copy->age_protect( $copy->age_protect->id )
1011 if ref $copy->age_protect;
1013 fix_copy_price($copy);
1015 return $editor->event unless $editor->update_asset_copy($copy);
1016 return remove_empty_objects($editor, $override, $orig_vol);
1020 sub remove_empty_objects {
1021 my( $editor, $override, $vol ) = @_;
1022 if( title_is_empty($editor, $vol->record) ) {
1024 # disable the TITLE_LAST_COPY event for now
1028 # delete this volume if it's not already marked as deleted
1029 unless( $U->is_true($vol->deleted) || $vol->isdeleted ) {
1031 $vol->editor($editor->requestor->id);
1032 $vol->edit_date('now');
1033 $editor->update_asset_call_number($vol) or return $editor->event;
1036 my $evt = delete_rec($editor, $vol->record);
1037 return $evt if $evt;
1040 return OpenILS::Event->new('TITLE_LAST_COPY', payload => $vol->record );
1047 # marks a record as deleted
1049 my( $editor, $rec_id ) = @_;
1051 my $rec = $editor->retrieve_biblio_record_entry($rec_id)
1052 or return $editor->event;
1054 return undef if $U->is_true($rec->deleted);
1058 $rec->editor( $editor->requestor->id );
1059 $rec->edit_date('now');
1060 $editor->update_biblio_record_entry($rec) or return $editor->event;
1067 my( $editor, $override, $vol, $copy ) = @_;
1069 my $stat = $U->copy_status($copy->status)->id;
1072 return OpenILS::Event->new('COPY_DELETE_WARNING', payload => $copy->id )
1073 if $stat == OILS_COPY_STATUS_CHECKED_OUT or
1074 $stat == OILS_COPY_STATUS_IN_TRANSIT or
1075 $stat == OILS_COPY_STATUS_ON_HOLDS_SHELF or
1076 $stat == OILS_COPY_STATUS_ILL;
1079 $logger->info("vol-update: deleting copy ".$copy->id);
1080 $copy->deleted('t');
1082 $copy->editor($editor->requestor->id);
1083 $copy->edit_date('now');
1084 $editor->update_asset_copy($copy) or return $editor->event;
1086 # Delete any open transits for this copy
1087 my $transits = $editor->search_action_transit_copy(
1088 { target_copy=>$copy->id, dest_recv_time => undef } );
1090 for my $t (@$transits) {
1091 $editor->delete_action_transit_copy($t)
1092 or return $editor->event;
1095 return remove_empty_objects($editor, $override, $vol);
1100 my( $editor, $vol, $copy ) = @_;
1102 my $existing = $editor->search_asset_copy(
1103 { barcode => $copy->barcode, deleted => 'f' } );
1105 return OpenILS::Event->new('ITEM_BARCODE_EXISTS') if @$existing;
1108 my $org = (ref $copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
1109 return $evt if ( $evt = org_cannot_have_vols($editor, $org) );
1112 $copy->creator($editor->requestor->id);
1113 $copy->create_date('now');
1114 fix_copy_price($copy);
1116 $editor->create_asset_copy($copy) or return $editor->event;
1120 # if 'delete_stats' is true, the copy->stat_cat_entries data is
1121 # treated as the authoritative list for the copy. existing entries
1122 # that are not in said list will be deleted from the DB
1123 sub update_copy_stat_entries {
1124 my( $editor, $copy, $delete_stats ) = @_;
1126 return undef if $copy->isdeleted;
1127 return undef unless $copy->ischanged or $copy->isnew;
1130 my $entries = $copy->stat_cat_entries;
1132 if( $delete_stats ) {
1133 $entries = ($entries and @$entries) ? $entries : [];
1135 return undef unless ($entries and @$entries);
1138 my $maps = $editor->search_asset_stat_cat_entry_copy_map({owning_copy=>$copy->id});
1141 # if there is no stat cat entry on the copy who's id matches the
1142 # current map's id, remove the map from the database
1143 for my $map (@$maps) {
1144 if(! grep { $_->id == $map->stat_cat_entry } @$entries ) {
1146 $logger->info("copy update found stale ".
1147 "stat cat entry map ".$map->id. " on copy ".$copy->id);
1149 $editor->delete_asset_stat_cat_entry_copy_map($map)
1150 or return $editor->event;
1155 # go through the stat cat update/create process
1156 for my $entry (@$entries) {
1159 # if this link already exists in the DB, don't attempt to re-create it
1160 next if( grep{$_->stat_cat_entry == $entry->id} @$maps );
1162 my $new_map = Fieldmapper::asset::stat_cat_entry_copy_map->new();
1164 my $sc = ref($entry->stat_cat) ? $entry->stat_cat->id : $entry->stat_cat;
1166 $new_map->stat_cat( $sc );
1167 $new_map->stat_cat_entry( $entry->id );
1168 $new_map->owning_copy( $copy->id );
1170 $editor->create_asset_stat_cat_entry_copy_map($new_map)
1171 or return $editor->event;
1173 $logger->info("copy update created new stat cat entry map ".$editor->data);
1181 my( $override, $editor, $vol ) = @_;
1184 return $evt if ( $evt = org_cannot_have_vols($editor, $vol->owning_lib) );
1186 # first lets see if there are any collisions
1187 my $vols = $editor->search_asset_call_number( {
1188 owning_lib => $vol->owning_lib,
1189 record => $vol->record,
1190 label => $vol->label,
1198 $label = $vol->label;
1200 return OpenILS::Event->new(
1201 'VOLUME_LABEL_EXISTS', payload => $vol->id);
1205 # create a temp label so we can create the volume, then de-dup it
1206 $vol->label( '__SYSTEM_TMP_'.time) if $label;
1208 $vol->creator($editor->requestor->id);
1209 $vol->create_date('now');
1210 $vol->editor($editor->requestor->id);
1211 $vol->edit_date('now');
1214 $editor->create_asset_call_number($vol) or return $editor->event;
1217 # now restore the label and merge into the existing record
1218 $vol->label($label);
1220 OpenILS::Application::Cat::Merge::merge_volumes($editor, [$vol], $$vols[0]);
1221 return $evt if $evt;
1228 __PACKAGE__->register_method (
1229 method => 'batch_volume_transfer',
1230 api_name => 'open-ils.cat.asset.volume.batch.transfer',
1233 __PACKAGE__->register_method (
1234 method => 'batch_volume_transfer',
1235 api_name => 'open-ils.cat.asset.volume.batch.transfer.override',
1239 sub batch_volume_transfer {
1240 my( $self, $conn, $auth, $args ) = @_;
1243 my $rec = $$args{docid};
1244 my $o_lib = $$args{lib};
1245 my $vol_ids = $$args{volumes};
1247 my $override = 1 if $self->api_name =~ /override/;
1249 $logger->info("merge: transferring volumes to lib=$o_lib and record=$rec");
1251 my $e = new_editor(authtoken => $auth, xact =>1);
1252 return $e->event unless $e->checkauth;
1253 return $e->event unless $e->allowed('VOLUME_UPDATE', $o_lib);
1255 my $dorg = $e->retrieve_actor_org_unit($o_lib)
1256 or return $e->event;
1258 my $ou_type = $e->retrieve_actor_org_unit_type($dorg->ou_type)
1259 or return $e->event;
1261 return $evt if ( $evt = org_cannot_have_vols($e, $o_lib) );
1263 my $vols = $e->batch_retrieve_asset_call_number($vol_ids);
1268 for my $vol (@$vols) {
1270 # if we've already looked at this volume, go to the next
1271 next if !$vol or grep { $vol->id == $_ } @seen;
1273 # grab all of the volumes in the list that have
1274 # the same label so they can be merged
1275 my @all = grep { $_->label eq $vol->label } @$vols;
1277 # take note of the fact that we've looked at this set of volumes
1278 push( @seen, $_->id ) for @all;
1279 push( @rec_ids, $_->record ) for @all;
1281 # for each volume, see if there are any copies that have a
1282 # remote circ_lib (circ_lib != vol->owning_lib and != $o_lib ).
1284 unless( $override ) {
1287 $logger->debug("merge: searching for copies with remote circ_lib for volume ".$v->id);
1289 call_number => $v->id,
1290 circ_lib => { "not in" => [ $o_lib, $v->owning_lib ] },
1294 my $copies = $e->search_asset_copy($args, {idlist=>1});
1296 # if the copy's circ_lib matches the destination lib,
1298 return OpenILS::Event->new('COPY_REMOTE_CIRC_LIB') if @$copies;
1302 # see if there is a volume at the destination lib that
1303 # already has the requested label
1304 my $existing_vol = $e->search_asset_call_number(
1306 label => $vol->label,
1308 owning_lib =>$o_lib,
1313 if( $existing_vol ) {
1315 if( grep { $_->id == $existing_vol->id } @all ) {
1316 # this volume is already accounted for in our list of volumes to merge
1317 $existing_vol = undef;
1320 # this volume exists on the destination record/owning_lib and must
1321 # be used as the destination for merging
1322 $logger->debug("merge: volume already exists at destination record: ".
1323 $existing_vol->id.' : '.$existing_vol->label) if $existing_vol;
1327 if( @all > 1 || $existing_vol ) {
1328 $logger->info("merge: found collisions in volume transfer");
1329 my @args = ($e, \@all);
1330 @args = ($e, \@all, $existing_vol) if $existing_vol;
1331 ($vol, $evt) = OpenILS::Application::Cat::Merge::merge_volumes(@args);
1332 return $evt if $evt;
1335 if( !$existing_vol ) {
1337 $vol->owning_lib($o_lib);
1339 $vol->editor($e->requestor->id);
1340 $vol->edit_date('now');
1342 $logger->info("merge: updating volume ".$vol->id);
1343 $e->update_asset_call_number($vol) or return $e->event;
1346 $logger->info("merge: bypassing volume update because existing volume used as target");
1349 # regardless of what volume was used as the destination,
1350 # update any copies that have moved over to the new lib
1351 my $copies = $e->search_asset_copy({call_number=>$vol->id, deleted => 'f'});
1353 # update circ lib on the copies - make this a method flag?
1354 for my $copy (@$copies) {
1355 next if $copy->circ_lib == $o_lib;
1356 $logger->info("merge: transfer moving circ lib on copy ".$copy->id);
1357 $copy->circ_lib($o_lib);
1358 $copy->editor($e->requestor->id);
1359 $copy->edit_date('now');
1360 $e->update_asset_copy($copy) or return $e->event;
1363 # Now see if any empty records need to be deleted after all of this
1366 $logger->debug("merge: seeing if we should delete record $_...");
1367 $evt = delete_rec($e, $_) if title_is_empty($e, $_);
1368 return $evt if $evt;
1372 # $evt = remove_empty_objects($e, $override, $_);
1376 $logger->info("merge: transfer succeeded");
1383 sub org_cannot_have_vols {
1387 my $org = $e->retrieve_actor_org_unit($org_id)
1388 or return $e->event;
1390 my $ou_type = $e->retrieve_actor_org_unit_type($org->ou_type)
1391 or return $e->event;
1393 return OpenILS::Event->new('ORG_CANNOT_HAVE_VOLS')
1394 unless $U->is_true($ou_type->can_have_vols);
1402 __PACKAGE__->register_method(
1403 api_name => 'open-ils.cat.call_number.find_or_create',
1404 method => 'find_or_create_volume',
1407 sub find_or_create_volume {
1408 my( $self, $conn, $auth, $label, $record_id, $org_id ) = @_;
1409 my $e = new_editor(authtoken=>$auth, xact=>1);
1410 return $e->die_event unless $e->checkauth;
1412 my $vol = $e->search_asset_call_number(
1413 {label => $label, record => $record_id, owning_lib => $org_id, deleted => 'f'},
1417 # If the volume exists, return the ID
1418 if( $vol ) { $e->rollback; return $vol; }
1420 # -----------------------------------------------------------------
1421 # Otherwise, create a new volume with the given attributes
1422 # -----------------------------------------------------------------
1424 return $e->die_event unless $e->allowed('VOLUME_UPDATE', $org_id);
1426 $vol = Fieldmapper::asset::call_number->new;
1427 $vol->owning_lib($org_id);
1428 $vol->label($label);
1429 $vol->record($record_id);
1430 $vol->creator($e->requestor->id);
1431 $vol->create_date('now');
1432 $vol->editor($e->requestor->id);
1433 $vol->edit_date('now');
1435 $e->create_asset_call_number($vol) or return $e->die_event;