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);
197 my $e = new_editor(authtoken=>$auth, xact=>1);
199 return $e->die_event unless $e->checkauth;
200 return $e->die_event unless $e->allowed('CREATE_MARC');
202 my $rec = $e->retrieve_biblio_record_entry($recid)
203 or return $e->die_event;
205 my $fixtcn = 1 if $self->api_name =~ /replace/o;
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/;
212 my $storage = OpenSRF::AppSession->create('open-ils.storage');
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
217 my( $tcn, $tsource, $marcdoc, $evt) =
218 _find_tcn_info($storage, $newxml, $override, $recid);
223 $rec->tcn_value($tcn);
224 $rec->tcn_source($tsource);
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 ) );
232 $logger->activity("user ".$e->requestor->id." replacing MARC for record $recid");
234 $e->update_biblio_record_entry($rec) or return $e->event;
237 $conn->respond_complete($rec);
241 'open-ils.ingest.full.biblio.record', $recid );
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/);
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
263 user_session must have IMPORT_MARC permissions
267 sub biblio_record_xml_import {
268 my( $self, $client, $authtoken, $xml, $source, $auto_tcn) = @_;
270 my $override = 1 if $self->api_name =~ /override/;
272 my( $tcn, $tcn_source, $marcdoc );
273 my( $requestor, $evt ) = $U->checksesperm($authtoken, 'IMPORT_MARC');
276 my $session = $apputils->start_db_session();
279 # auto_tcn forces a blank TCN value so the DB will have to generate one for us
280 $marcdoc = __make_marc_doc($xml);
282 ( $tcn, $tcn_source, $marcdoc, $evt ) = _find_tcn_info($session, $xml, $override);
286 $logger->info("user ".$requestor->id.
287 " creating new biblio entry with tcn=$tcn and tcn_source $tcn_source");
289 my $record = Fieldmapper::biblio::record_entry->new;
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 ) );
300 my $id = $session->request(
301 "open-ils.storage.direct.biblio.record_entry.create", $record )->gather(1);
303 return $U->DB_UPDATE_FAILED($record) unless $id;
306 $logger->info("marc create/import created new record $id");
308 $apputils->commit_db_session($session);
310 $logger->debug("Sending record off to be wormized");
312 $client->respond_complete($record);
316 'open-ils.ingest.full.biblio.record', $id );
321 sub __make_marc_doc {
323 my $marcxml = XML::LibXML->new->parse_string( $xml );
324 $marcxml->documentElement->setNamespace(
325 "http://www.loc.gov/MARC21/slim", "marc", 1 );
333 my $override = shift;
334 my $existing_rec = shift || 0;
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 );
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");
346 $xpath = '//marc:controlfield[@tag="003"]';
347 my $tcn_source = $marcxml->documentElement->findvalue($xpath) || "System Local";
349 if(my $rec = _tcn_exists($session, $tcn, $tcn_source, $existing_rec) ) {
352 $tcn = find_free_tcn( $marcxml, $session, $existing_rec );
354 # if we're overriding, try to find a different TCN to use
357 # XXX Create ALLOW_ALT_TCN permission check support
359 $logger->info("tcn value $tcn already exists, attempting to override");
367 'OPEN_TCN_NOT_FOUND',
368 payload => $marcxml->toString())
374 $logger->warn("tcn value $origtcn already exists in import/create");
376 # otherwise, return event
382 'TCN_EXISTS', payload => {
392 return ($tcn, $tcn_source, $marcxml);
399 my $existing_rec = shift;
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";
408 if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {
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;}
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;}
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;}
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;}
443 $marcxml->documentElement->removeChild(
444 $marcxml->documentElement->findnodes( '//datafield[@tag="035"]' )
449 return undef unless $tcn;
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 );
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 );
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 );
478 my $existing_rec = shift || 0;
480 if(!$tcn) {return 0;}
482 $logger->debug("tcn_exists search for tcn $tcn and source $source and id $existing_rec");
484 # XXX why does the source matter?
485 # my $req = $session->request(
486 # { tcn_value => $tcn, tcn_source => $source, deleted => 'f' } );
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} } );
492 my $recs = $req->gather(1);
494 if($recs and $recs->[0]) {
495 $logger->debug("_tcn_exists is true for tcn : $tcn ($source)");
499 $logger->debug("_tcn_exists is false for tcn : $tcn ($source)");
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",
512 sub biblio_record_record_metadata {
513 my( $self, $client, $authtoken, $ids ) = @_;
515 return [] unless $ids and @$ids;
517 my $editor = new_editor(authtoken => $authtoken);
518 return $editor->event unless $editor->checkauth;
519 return $editor->event unless $editor->allowed('VIEW_USER');
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 );
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 )
543 sub biblio_record_marc_cn {
544 my( $self, $client, $id ) = @_;
546 my $session = OpenSRF::AppSession->create("open-ils.cstore");
548 ->request("open-ils.cstore.direct.biblio.record_entry.retrieve", $id )
552 my $doc = XML::LibXML->new->parse_string($marc);
553 $doc->documentElement->setNamespace( "http://www.loc.gov/MARC21/slim", "marc", 1 );
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']");
559 my $cn = $x->findvalue("marc:subfield[\@code='a' or \@code='b']");
560 push @res, {$tag => $cn} if ($cn);
567 sub _get_id_by_userid {
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 } );
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");
582 if(UNIVERSAL::isa( $response, "Error")){
583 throw $response ($response);
586 for my $u (@{$response->content}) {
592 $session->disconnect;
599 # commits metadata objects to the db
600 sub _update_record_metadata {
602 my ($session, @docs ) = @_;
604 for my $doc (@docs) {
606 my $user_obj = $doc->{user};
607 my $docid = $doc->{docid};
609 warn "Updating metata for doc $docid\n";
611 my $request = $session->request(
612 "open-ils.storage.direct.biblio.record_entry.retrieve", $docid );
613 my $record = $request->gather(1);
615 warn "retrieved record\n";
616 my ($id) = _get_id_by_userid($user_obj->usrname);
618 warn "got $id from _get_id_by_userid\n";
619 $record->editor($id);
621 warn "Grabbed the record, updating and moving on\n";
623 $request = $session->request(
624 "open-ils.storage.direct.biblio.record_entry.update", $record );
628 warn "committing metarecord update\n";
635 __PACKAGE__->register_method(
636 method => "orgs_for_title",
637 api_name => "open-ils.cat.actor.org_unit.retrieve_by_title"
641 my( $self, $client, $record_id ) = @_;
643 my $vols = $apputils->simple_scalar_request(
645 "open-ils.cstore.direct.asset.call_number.search.atomic",
646 { record => $record_id, deleted => 'f' });
648 my $orgs = { map {$_->owning_lib => 1 } @$vols };
649 return [ keys %$orgs ];
653 __PACKAGE__->register_method(
654 method => "retrieve_copies",
655 api_name => "open-ils.cat.asset.copy_tree.retrieve");
657 __PACKAGE__->register_method(
658 method => "retrieve_copies",
659 api_name => "open-ils.cat.asset.copy_tree.global.retrieve");
661 # user_session may be null/undef
662 sub retrieve_copies {
664 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
666 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
670 warn " $$ retrieving copy tree for orgs @org_ids and doc $docid at " . time() . "\n";
672 # grabbing copy trees should be available for everyone..
673 if(!@org_ids and $user_session) {
675 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
676 @org_ids = ($user_obj->home_ou);
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' } );
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 );
693 warn " $$ Finished copy_tree at " . time() . "\n";
701 sub _build_volume_list {
702 my $search_hash = shift;
704 $search_hash->{deleted} = 'f';
705 my $e = new_editor();
707 my $vols = $e->search_asset_call_number($search_hash);
711 for my $volume (@$vols) {
713 my $copies = $e->search_asset_copy(
714 { call_number => $volume->id , deleted => 'f' });
716 $copies = [ sort { $a->barcode cmp $b->barcode } @$copies ];
718 for my $c (@$copies) {
719 if( $c->status == OILS_COPY_STATUS_CHECKED_OUT ) {
721 $e->search_action_circulation(
723 { target_copy => $c->id },
725 order_by => { circ => 'xact_start desc' },
734 $volume->copies($copies);
735 push( @volumes, $volume );
738 #$session->disconnect();
744 __PACKAGE__->register_method(
745 method => "fleshed_copy_update",
746 api_name => "open-ils.cat.asset.copy.fleshed.batch.update",);
748 __PACKAGE__->register_method(
749 method => "fleshed_copy_update",
750 api_name => "open-ils.cat.asset.copy.fleshed.batch.update.override",);
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);
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);
762 $logger->info("fleshed copy update failed with event: ".JSON->perl2JSON($evt));
767 $logger->info("fleshed copy update successfully updated ".scalar(@$copies)." copies");
772 __PACKAGE__->register_method(
774 api_name => 'open-ils.cat.biblio.records.merge',
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.
786 my( $self, $conn, $auth, $master, $records ) = @_;
787 my( $reqr, $evt ) = $U->checkses($auth);
789 my $editor = new_editor( requestor => $reqr, xact => 1 );
790 my $v = OpenILS::Application::Cat::Merge::merge_records($editor, $master, $records);
799 # ---------------------------------------------------------------------------
800 # ---------------------------------------------------------------------------
802 # returns true if the given title (id) has no un-deleted
805 my( $editor, $rid ) = @_;
807 return 0 if $rid == OILS_PRECAT_RECORD;
809 my $cnlist = $editor->search_asset_call_number(
810 { record => $rid, deleted => 'f' }, { idlist => 1 } );
811 return 1 unless @$cnlist;
813 for my $cn (@$cnlist) {
814 my $copylist = $editor->search_asset_copy(
816 { call_number => $cn, deleted => 'f' },
819 return 0 if @$copylist; # false if we find any copies
826 __PACKAGE__->register_method(
827 method => "fleshed_volume_update",
828 api_name => "open-ils.cat.asset.volume.fleshed.batch.update",);
830 __PACKAGE__->register_method(
831 method => "fleshed_volume_update",
832 api_name => "open-ils.cat.asset.volume.fleshed.batch.update.override",);
834 sub fleshed_volume_update {
835 my( $self, $conn, $auth, $volumes, $delete_stats ) = @_;
836 my( $reqr, $evt ) = $U->checkses($auth);
839 my $override = ($self->api_name =~ /override/);
840 my $editor = new_editor( requestor => $reqr, xact => 1 );
842 for my $vol (@$volumes) {
843 $logger->info("vol-update: investigating volume ".$vol->id);
845 $vol->editor($reqr->id);
846 $vol->edit_date('now');
848 my $copies = $vol->copies;
851 $vol->editor($editor->requestor->id);
852 $vol->edit_date('now');
854 if( $vol->isdeleted ) {
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;
863 return $editor->event unless
864 $editor->update_asset_call_number($vol);
867 } elsif( $vol->isnew ) {
868 $logger->info("vol-update: creating volume");
869 $evt = create_volume( $override, $editor, $vol );
872 } elsif( $vol->ischanged ) {
873 $logger->info("vol-update: update volume");
874 $evt = update_volume($vol, $editor);
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 );
887 return scalar(@$volumes);
896 return $evt if ( $evt = org_cannot_have_vols($editor, $vol->owning_lib) );
898 my $vols = $editor->search_asset_call_number( {
899 owning_lib => $vol->owning_lib,
900 record => $vol->record,
901 label => $vol->label,
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;
910 return $editor->event unless $editor->update_asset_call_number($vol);
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;
922 $logger->debug("using copy perm org $org");
927 # this does the actual work
928 sub update_fleshed_copies {
929 my( $editor, $override, $vol, $copies, $delete_stats ) = @_;
932 my $fetchvol = ($vol) ? 0 : 1;
935 $cache{$vol->id} = $vol if $vol;
937 for my $copy (@$copies) {
939 my $copyid = $copy->id;
940 $logger->info("vol-update: inspecting copy $copyid");
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;
948 return $editor->event unless
949 $editor->allowed('UPDATE_COPY', copy_perm_org($vol, $copy));
951 $copy->editor($editor->requestor->id);
952 $copy->edit_date('now');
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);
958 my $sc_entries = $copy->stat_cat_entries;
959 $copy->clear_stat_cat_entries;
961 if( $copy->isdeleted ) {
962 $evt = delete_copy($editor, $override, $vol, $copy);
965 } elsif( $copy->isnew ) {
966 $evt = create_copy( $editor, $vol, $copy );
969 } elsif( $copy->ischanged ) {
971 $evt = update_copy( $editor, $override, $vol, $copy );
975 $copy->stat_cat_entries( $sc_entries );
976 $evt = update_copy_stat_entries($editor, $copy, $delete_stats);
980 $logger->debug("vol-update: done updating copy batch");
987 my $p = $copy->price || 0;
991 my $d = $copy->deposit_amount || 0;
993 $copy->deposit_amount($d);
998 my( $editor, $override, $vol, $copy ) = @_;
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) );
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);
1008 $copy->editor($editor->requestor->id);
1009 $copy->edit_date('now');
1011 $copy->age_protect( $copy->age_protect->id )
1012 if ref $copy->age_protect;
1014 fix_copy_price($copy);
1016 return $editor->event unless $editor->update_asset_copy($copy);
1017 return remove_empty_objects($editor, $override, $orig_vol);
1021 sub remove_empty_objects {
1022 my( $editor, $override, $vol ) = @_;
1023 if( title_is_empty($editor, $vol->record) ) {
1025 # disable the TITLE_LAST_COPY event for now
1029 # delete this volume if it's not already marked as deleted
1030 unless( $U->is_true($vol->deleted) || $vol->isdeleted ) {
1032 $vol->editor($editor->requestor->id);
1033 $vol->edit_date('now');
1034 $editor->update_asset_call_number($vol) or return $editor->event;
1037 my $evt = delete_rec($editor, $vol->record);
1038 return $evt if $evt;
1041 return OpenILS::Event->new('TITLE_LAST_COPY', payload => $vol->record );
1048 # marks a record as deleted
1050 my( $editor, $rec_id ) = @_;
1052 my $rec = $editor->retrieve_biblio_record_entry($rec_id)
1053 or return $editor->event;
1055 return undef if $U->is_true($rec->deleted);
1059 $rec->editor( $editor->requestor->id );
1060 $rec->edit_date('now');
1061 $editor->update_biblio_record_entry($rec) or return $editor->event;
1068 my( $editor, $override, $vol, $copy ) = @_;
1070 return $editor->event unless
1071 $editor->allowed('DELETE_COPY',copy_perm_org($vol, $copy));
1073 my $stat = $U->copy_status($copy->status)->id;
1076 return OpenILS::Event->new('COPY_DELETE_WARNING', payload => $copy->id )
1077 if $stat == OILS_COPY_STATUS_CHECKED_OUT or
1078 $stat == OILS_COPY_STATUS_IN_TRANSIT or
1079 $stat == OILS_COPY_STATUS_ON_HOLDS_SHELF or
1080 $stat == OILS_COPY_STATUS_ILL;
1083 $logger->info("vol-update: deleting copy ".$copy->id);
1084 $copy->deleted('t');
1086 $copy->editor($editor->requestor->id);
1087 $copy->edit_date('now');
1088 $editor->update_asset_copy($copy) or return $editor->event;
1090 # Delete any open transits for this copy
1091 my $transits = $editor->search_action_transit_copy(
1092 { target_copy=>$copy->id, dest_recv_time => undef } );
1094 for my $t (@$transits) {
1095 $editor->delete_action_transit_copy($t)
1096 or return $editor->event;
1099 return remove_empty_objects($editor, $override, $vol);
1104 my( $editor, $vol, $copy ) = @_;
1106 my $existing = $editor->search_asset_copy(
1107 { barcode => $copy->barcode, deleted => 'f' } );
1109 return OpenILS::Event->new('ITEM_BARCODE_EXISTS') if @$existing;
1111 # see if the volume this copy references is marked as deleted
1112 my $evol = $editor->retrieve_asset_call_number($copy->call_number)
1113 or return $editor->event;
1114 return OpenILS::Event->new('VOLUME_DELETED', vol => $evol->id)
1115 if $U->is_true($evol->deleted);
1118 my $org = (ref $copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
1119 return $evt if ( $evt = org_cannot_have_vols($editor, $org) );
1122 $copy->creator($editor->requestor->id);
1123 $copy->create_date('now');
1124 fix_copy_price($copy);
1126 $editor->create_asset_copy($copy) or return $editor->event;
1130 # if 'delete_stats' is true, the copy->stat_cat_entries data is
1131 # treated as the authoritative list for the copy. existing entries
1132 # that are not in said list will be deleted from the DB
1133 sub update_copy_stat_entries {
1134 my( $editor, $copy, $delete_stats ) = @_;
1136 return undef if $copy->isdeleted;
1137 return undef unless $copy->ischanged or $copy->isnew;
1140 my $entries = $copy->stat_cat_entries;
1142 if( $delete_stats ) {
1143 $entries = ($entries and @$entries) ? $entries : [];
1145 return undef unless ($entries and @$entries);
1148 my $maps = $editor->search_asset_stat_cat_entry_copy_map({owning_copy=>$copy->id});
1151 # if there is no stat cat entry on the copy who's id matches the
1152 # current map's id, remove the map from the database
1153 for my $map (@$maps) {
1154 if(! grep { $_->id == $map->stat_cat_entry } @$entries ) {
1156 $logger->info("copy update found stale ".
1157 "stat cat entry map ".$map->id. " on copy ".$copy->id);
1159 $editor->delete_asset_stat_cat_entry_copy_map($map)
1160 or return $editor->event;
1165 # go through the stat cat update/create process
1166 for my $entry (@$entries) {
1169 # if this link already exists in the DB, don't attempt to re-create it
1170 next if( grep{$_->stat_cat_entry == $entry->id} @$maps );
1172 my $new_map = Fieldmapper::asset::stat_cat_entry_copy_map->new();
1174 my $sc = ref($entry->stat_cat) ? $entry->stat_cat->id : $entry->stat_cat;
1176 $new_map->stat_cat( $sc );
1177 $new_map->stat_cat_entry( $entry->id );
1178 $new_map->owning_copy( $copy->id );
1180 $editor->create_asset_stat_cat_entry_copy_map($new_map)
1181 or return $editor->event;
1183 $logger->info("copy update created new stat cat entry map ".$editor->data);
1191 my( $override, $editor, $vol ) = @_;
1194 return $evt if ( $evt = org_cannot_have_vols($editor, $vol->owning_lib) );
1196 # see if the record this volume references is marked as deleted
1197 my $rec = $editor->retrieve_biblio_record_entry($vol->record)
1198 or return $editor->event;
1199 return OpenILS::Event->new('BIB_RECORD_DELETED', rec => $rec->id)
1200 if $U->is_true($rec->deleted);
1202 # first lets see if there are any collisions
1203 my $vols = $editor->search_asset_call_number( {
1204 owning_lib => $vol->owning_lib,
1205 record => $vol->record,
1206 label => $vol->label,
1213 # we've found an exising volume
1215 $label = $vol->label;
1217 return OpenILS::Event->new(
1218 'VOLUME_LABEL_EXISTS', payload => $vol->id);
1222 # create a temp label so we can create the new volume,
1223 # then de-dup it with the existing volume
1224 $vol->label( "__SYSTEM_TMP_$$".time) if $label;
1226 $vol->creator($editor->requestor->id);
1227 $vol->create_date('now');
1228 $vol->editor($editor->requestor->id);
1229 $vol->edit_date('now');
1232 $editor->create_asset_call_number($vol) or return $editor->event;
1235 # now restore the label and merge into the existing record
1236 $vol->label($label);
1238 OpenILS::Application::Cat::Merge::merge_volumes($editor, [$vol], $$vols[0]);
1239 return $evt if $evt;
1246 __PACKAGE__->register_method (
1247 method => 'batch_volume_transfer',
1248 api_name => 'open-ils.cat.asset.volume.batch.transfer',
1251 __PACKAGE__->register_method (
1252 method => 'batch_volume_transfer',
1253 api_name => 'open-ils.cat.asset.volume.batch.transfer.override',
1257 sub batch_volume_transfer {
1258 my( $self, $conn, $auth, $args ) = @_;
1261 my $rec = $$args{docid};
1262 my $o_lib = $$args{lib};
1263 my $vol_ids = $$args{volumes};
1265 my $override = 1 if $self->api_name =~ /override/;
1267 $logger->info("merge: transferring volumes to lib=$o_lib and record=$rec");
1269 my $e = new_editor(authtoken => $auth, xact =>1);
1270 return $e->event unless $e->checkauth;
1271 return $e->event unless $e->allowed('VOLUME_UPDATE', $o_lib);
1273 my $dorg = $e->retrieve_actor_org_unit($o_lib)
1274 or return $e->event;
1276 my $ou_type = $e->retrieve_actor_org_unit_type($dorg->ou_type)
1277 or return $e->event;
1279 return $evt if ( $evt = org_cannot_have_vols($e, $o_lib) );
1281 my $vols = $e->batch_retrieve_asset_call_number($vol_ids);
1286 for my $vol (@$vols) {
1288 # if we've already looked at this volume, go to the next
1289 next if !$vol or grep { $vol->id == $_ } @seen;
1291 # grab all of the volumes in the list that have
1292 # the same label so they can be merged
1293 my @all = grep { $_->label eq $vol->label } @$vols;
1295 # take note of the fact that we've looked at this set of volumes
1296 push( @seen, $_->id ) for @all;
1297 push( @rec_ids, $_->record ) for @all;
1299 # for each volume, see if there are any copies that have a
1300 # remote circ_lib (circ_lib != vol->owning_lib and != $o_lib ).
1302 unless( $override ) {
1305 $logger->debug("merge: searching for copies with remote circ_lib for volume ".$v->id);
1307 call_number => $v->id,
1308 circ_lib => { "not in" => [ $o_lib, $v->owning_lib ] },
1312 my $copies = $e->search_asset_copy($args, {idlist=>1});
1314 # if the copy's circ_lib matches the destination lib,
1316 return OpenILS::Event->new('COPY_REMOTE_CIRC_LIB') if @$copies;
1320 # see if there is a volume at the destination lib that
1321 # already has the requested label
1322 my $existing_vol = $e->search_asset_call_number(
1324 label => $vol->label,
1326 owning_lib =>$o_lib,
1331 if( $existing_vol ) {
1333 if( grep { $_->id == $existing_vol->id } @all ) {
1334 # this volume is already accounted for in our list of volumes to merge
1335 $existing_vol = undef;
1338 # this volume exists on the destination record/owning_lib and must
1339 # be used as the destination for merging
1340 $logger->debug("merge: volume already exists at destination record: ".
1341 $existing_vol->id.' : '.$existing_vol->label) if $existing_vol;
1345 if( @all > 1 || $existing_vol ) {
1346 $logger->info("merge: found collisions in volume transfer");
1347 my @args = ($e, \@all);
1348 @args = ($e, \@all, $existing_vol) if $existing_vol;
1349 ($vol, $evt) = OpenILS::Application::Cat::Merge::merge_volumes(@args);
1350 return $evt if $evt;
1353 if( !$existing_vol ) {
1355 $vol->owning_lib($o_lib);
1357 $vol->editor($e->requestor->id);
1358 $vol->edit_date('now');
1360 $logger->info("merge: updating volume ".$vol->id);
1361 $e->update_asset_call_number($vol) or return $e->event;
1364 $logger->info("merge: bypassing volume update because existing volume used as target");
1367 # regardless of what volume was used as the destination,
1368 # update any copies that have moved over to the new lib
1369 my $copies = $e->search_asset_copy({call_number=>$vol->id, deleted => 'f'});
1371 # update circ lib on the copies - make this a method flag?
1372 for my $copy (@$copies) {
1373 next if $copy->circ_lib == $o_lib;
1374 $logger->info("merge: transfer moving circ lib on copy ".$copy->id);
1375 $copy->circ_lib($o_lib);
1376 $copy->editor($e->requestor->id);
1377 $copy->edit_date('now');
1378 $e->update_asset_copy($copy) or return $e->event;
1381 # Now see if any empty records need to be deleted after all of this
1384 $logger->debug("merge: seeing if we should delete record $_...");
1385 $evt = delete_rec($e, $_) if title_is_empty($e, $_);
1386 return $evt if $evt;
1390 # $evt = remove_empty_objects($e, $override, $_);
1394 $logger->info("merge: transfer succeeded");
1401 sub org_cannot_have_vols {
1405 my $org = $e->retrieve_actor_org_unit($org_id)
1406 or return $e->event;
1408 my $ou_type = $e->retrieve_actor_org_unit_type($org->ou_type)
1409 or return $e->event;
1411 return OpenILS::Event->new('ORG_CANNOT_HAVE_VOLS')
1412 unless $U->is_true($ou_type->can_have_vols);
1420 __PACKAGE__->register_method(
1421 api_name => 'open-ils.cat.call_number.find_or_create',
1422 method => 'find_or_create_volume',
1425 sub find_or_create_volume {
1426 my( $self, $conn, $auth, $label, $record_id, $org_id ) = @_;
1427 my $e = new_editor(authtoken=>$auth, xact=>1);
1428 return $e->die_event unless $e->checkauth;
1430 my $vol = $e->search_asset_call_number(
1431 {label => $label, record => $record_id, owning_lib => $org_id, deleted => 'f'},
1435 # If the volume exists, return the ID
1436 if( $vol ) { $e->rollback; return $vol; }
1438 # -----------------------------------------------------------------
1439 # Otherwise, create a new volume with the given attributes
1440 # -----------------------------------------------------------------
1442 return $e->die_event unless $e->allowed('VOLUME_UPDATE', $org_id);
1444 $vol = Fieldmapper::asset::call_number->new;
1445 $vol->owning_lib($org_id);
1446 $vol->label($label);
1447 $vol->record($record_id);
1449 #$vol->creator($e->requestor->id);
1450 #$vol->create_date('now');
1451 #$vol->editor($e->requestor->id);
1452 #$vol->edit_date('now');
1453 #$e->create_asset_call_number($vol) or return $e->die_event;
1455 my $evt = create_volume( 0, $e, $vol );
1456 return $evt if $evt;