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 ) = @_;
60 return $marctemplates{$type} if defined($marctemplates{$type});
61 $marctemplates{$type} = _load_marc_template($type);
62 return $marctemplates{$type};
65 sub _load_marc_template {
68 if(!$conf) { $conf = OpenSRF::Utils::SettingsClient->new; }
70 my $template = $conf->config_value(
71 "apps", "open-ils.cat","app_settings", "marctemplates", $type );
72 warn "Opening template file $template\n";
74 open( F, $template ) or
75 throw OpenSRF::EX::ERROR ("Unable to open MARC template file: $template : $@");
79 my $xml = join('', @xml);
81 return XML::LibXML->new->parse_string($xml)->documentElement->toString;
85 sub bib_source_from_name {
87 $logger->debug("searching for bib source: $name");
89 $__bib_sources = new_editor()->retrieve_all_config_bib_source()
90 unless $__bib_sources;
92 my ($s) = grep { lc($_->source) eq lc($name) } @$__bib_sources;
100 __PACKAGE__->register_method(
101 method => "create_record_xml",
102 api_name => "open-ils.cat.biblio.record.xml.create.override",
103 signature => q/@see open-ils.cat.biblio.record.xml.create/);
105 __PACKAGE__->register_method(
106 method => "create_record_xml",
107 api_name => "open-ils.cat.biblio.record.xml.create",
109 Inserts a new biblio with the given XML
113 sub create_record_xml {
114 my( $self, $client, $login, $xml, $source ) = @_;
116 my $override = 1 if $self->api_name =~ /override/;
118 my( $user_obj, $evt ) = $U->checksesperm($login, 'CREATE_MARC');
121 $logger->activity("user ".$user_obj->id." creating new MARC record");
123 my $meth = $self->method_lookup("open-ils.cat.biblio.record.xml.import");
125 $meth = $self->method_lookup(
126 "open-ils.cat.biblio.record.xml.import.override") if $override;
128 my ($s) = $meth->run($login, $xml, $source);
134 __PACKAGE__->register_method(
135 method => "biblio_record_replace_marc",
136 api_name => "open-ils.cat.biblio.record.xml.update",
139 Updates the XML for a given biblio record.
140 This does not change any other aspect of the record entry
141 exception the XML, the editor, and the edit date.
142 @return The update record object
146 __PACKAGE__->register_method(
147 method => 'biblio_record_replace_marc',
148 api_name => 'open-ils.cat.biblio.record.marc.replace',
150 @param auth The authtoken
151 @param recid The record whose MARC we're replacing
152 @param newxml The new xml to use
156 __PACKAGE__->register_method(
157 method => 'biblio_record_replace_marc',
158 api_name => 'open-ils.cat.biblio.record.marc.replace.override',
159 signature => q/@see open-ils.cat.biblio.record.marc.replace/
162 sub biblio_record_replace_marc {
163 my( $self, $conn, $auth, $recid, $newxml, $source ) = @_;
165 my $e = OpenILS::Utils::Editor->new(authtoken=>$auth, xact=>1);
167 return $e->event unless $e->checkauth;
168 return $e->event unless $e->allowed('CREATE_MARC');
170 my $rec = $e->retrieve_biblio_record_entry($recid)
173 my $fixtcn = 1 if $self->api_name =~ /replace/o;
175 # See if there is a different record in the database that has our TCN value
176 # If we're not updating the TCN, all we care about it the marcdoc
177 my $override = $self->api_name =~ /override/;
179 my $storage = OpenSRF::AppSession->create('open-ils.storage');
181 my( $tcn, $tsource, $marcdoc, $evt) =
182 _find_tcn_info($e->session, $newxml, $override, $recid);
187 $rec->tcn_value($tcn);
188 $rec->tcn_source($tsource);
191 $rec->source(bib_source_from_name($source)) if $source;
192 $rec->editor($e->requestor->id);
193 $rec->edit_date('now');
194 $rec->marc( entityize( $marcdoc->documentElement->toString ) );
196 $logger->activity("user ".$e->requestor->id." replacing MARC for record $recid");
198 $e->update_biblio_record_entry($rec) or return $e->event;
201 $conn->respond_complete($rec);
205 'open-ils.ingest.full.biblio.record', $recid );
213 __PACKAGE__->register_method(
214 method => "biblio_record_xml_import",
215 api_name => "open-ils.cat.biblio.record.xml.import.override",
216 signature => q/@see open-ils.cat.biblio.record.xml.import/);
218 __PACKAGE__->register_method(
219 method => "biblio_record_xml_import",
220 api_name => "open-ils.cat.biblio.record.xml.import",
221 notes => <<" NOTES");
222 Takes a marcxml record and imports the record into the database. In this
223 case, the marcxml record is assumed to be a complete record (i.e. valid
224 MARC). The title control number is taken from (whichever comes first)
225 tags 001, 039[ab], 020a, 022a, 010, 035a and whichever does not already exist
227 user_session must have IMPORT_MARC permissions
231 sub biblio_record_xml_import {
232 my( $self, $client, $authtoken, $xml, $source) = @_;
234 my $override = 1 if $self->api_name =~ /override/;
236 my( $tcn, $tcn_source, $marcdoc );
237 my( $requestor, $evt ) = $U->checksesperm($authtoken, 'IMPORT_MARC');
240 my $session = $apputils->start_db_session();
242 ( $tcn, $tcn_source, $marcdoc, $evt ) = _find_tcn_info($session, $xml, $override);
245 $logger->activity("user ".$requestor->id.
246 " creating new biblio entry with tcn=$tcn and tcn_source $tcn_source");
248 my $record = Fieldmapper::biblio::record_entry->new;
250 $record->source(bib_source_from_name($source)) if $source;
251 $record->tcn_source($tcn_source);
252 $record->tcn_value($tcn);
253 $record->creator($requestor->id);
254 $record->editor($requestor->id);
255 $record->create_date('now');
256 $record->edit_date('now');
257 $record->marc( entityize( $marcdoc->documentElement->toString ) );
259 my $id = $session->request(
260 "open-ils.storage.direct.biblio.record_entry.create", $record )->gather(1);
262 return $U->DB_UPDATE_FAILED($record) unless $id;
265 $logger->info("marc create/import created new record $id");
267 $apputils->commit_db_session($session);
269 $logger->debug("Sending record off to be wormized");
271 $client->respond_complete($record);
275 'open-ils.ingest.full.biblio.record', $id );
284 my $override = shift;
285 my $existing_rec = shift || 0;
288 my $marcxml = XML::LibXML->new->parse_string( $xml );
289 $marcxml->documentElement->setNamespace(
290 "http://www.loc.gov/MARC21/slim", "marc", 1 );
292 my $xpath = '//marc:controlfield[@tag="001"]';
293 my $tcn = $marcxml->documentElement->findvalue($xpath);
294 $logger->info("biblio import located 001 (tcn) value of $tcn");
296 $xpath = '//marc:controlfield[@tag="003"]';
297 my $tcn_source = $marcxml->documentElement->findvalue($xpath) || "System Local";
299 if(my $rec = _tcn_exists($session, $tcn, $tcn_source, $existing_rec) ) {
302 $tcn = find_free_tcn( $marcxml, $session, $existing_rec );
304 # if we're overriding, try to find a different TCN to use
307 $logger->activity("tcn value $tcn already exists, attempting to override");
315 'OPEN_TCN_NOT_FOUND',
316 payload => $marcxml->toString())
322 $logger->warn("tcn value $origtcn already exists in import/create");
324 # otherwise, return event
330 'TCN_EXISTS', payload => {
340 return ($tcn, $tcn_source, $marcxml);
347 my $existing_rec = shift;
351 my $xpath = '//marc:datafield[@tag="039"]/subfield[@code="a"]';
352 my ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
353 $xpath = '//marc:datafield[@tag="039"]/subfield[@code="b"]';
354 my $tcn_source = $marcxml->documentElement->findvalue($xpath) || "System Local";
356 if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {
364 $xpath = '//marc:datafield[@tag="020"]/subfield[@code="a"]';
365 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
366 $tcn_source = "ISBN";
367 if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
371 $xpath = '//marc:datafield[@tag="022"]/subfield[@code="a"]';
372 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
373 $tcn_source = "ISSN";
374 if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
378 $xpath = '//marc:datafield[@tag="010"]';
379 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
380 $tcn_source = "LCCN";
381 if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
385 $xpath = '//marc:datafield[@tag="035"]/subfield[@code="a"]';
386 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
387 $tcn_source = "System Legacy";
388 if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
391 $marcxml->documentElement->removeChild(
392 $marcxml->documentElement->findnodes( '//datafield[@tag="035"]' )
397 return undef unless $tcn;
400 my $df = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'datafield');
401 $df->setAttribute( tag => '039' );
402 $df->setAttribute( ind1 => ' ' );
403 $df->setAttribute( ind2 => ' ' );
404 $marcxml->documentElement->appendChild( $df );
406 my $sfa = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'subfield');
407 $sfa->setAttribute( code => 'a' );
408 $sfa->appendChild( $marcxml->createTextNode( $tcn ) );
409 $df->appendChild( $sfa );
411 my $sfb = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'subfield');
412 $sfb->setAttribute( code => 'b' );
413 $sfb->appendChild( $marcxml->createTextNode( $tcn_source ) );
414 $df->appendChild( $sfb );
426 my $existing_rec = shift || 0;
428 if(!$tcn) {return 0;}
430 $logger->debug("tcn_exists search for tcn $tcn and source $source and id $existing_rec");
432 # XXX why does the source matter?
433 # my $req = $session->request(
434 # { tcn_value => $tcn, tcn_source => $source, deleted => 'f' } );
436 my $req = $session->request(
437 "open-ils.storage.id_list.biblio.record_entry.search_where.atomic",
438 { tcn_value => $tcn, deleted => 'f', id => {'!=' => $existing_rec} } );
440 my $recs = $req->gather(1);
442 if($recs and $recs->[0]) {
443 $logger->debug("_tcn_exists is true for tcn : $tcn ($source)");
447 $logger->debug("_tcn_exists is false for tcn : $tcn ($source)");
454 # XXX deprecated. Remove me.
458 __PACKAGE__->register_method(
459 method => "biblio_record_tree_retrieve",
460 api_name => "open-ils.cat.biblio.record.tree.retrieve",
463 sub biblio_record_tree_retrieve {
465 my( $self, $client, $recordid ) = @_;
467 my $name = "open-ils.storage.direct.biblio.record_entry.retrieve";
468 my $session = OpenSRF::AppSession->create( "open-ils.storage" );
469 my $request = $session->request( $name, $recordid );
470 my $marcxml = $request->gather(1);
473 throw OpenSRF::EX::ERROR
474 ("No record in database with id $recordid");
477 $session->disconnect();
480 warn "turning into nodeset\n";
481 my $nodes = OpenILS::Utils::FlatXML->new()->xml_to_nodeset( $marcxml->marc );
482 warn "turning nodeset into tree\n";
483 my $tree = $utils->nodeset2tree( $nodes->nodeset );
485 $tree->owner_doc( $marcxml->id() );
487 warn "returning tree\n";
495 __PACKAGE__->register_method(
496 method => "biblio_record_xml_update",
497 api_name => "open-ils.cat.biblio.record.xml.update",
498 argc => 3, #(session_id, biblio_tree )
499 notes => <<' NOTES');
500 Updates the XML of a biblio record entry
501 @param authtoken The session token for the staff updating the record
502 @param docID The record entry ID to update
503 @param xml The new MARCXML record
506 sub biblio_record_xml_update {
508 my( $self, $client, $user_session, $id, $xml ) = @_;
510 my $user_obj = $apputils->check_user_session($user_session);
512 if($apputils->check_user_perms(
513 $user_obj->id, $user_obj->home_ou, "UPDATE_MARC")) {
514 return OpenILS::Perm->new("UPDATE_MARC");
517 $logger->activity("user ".$user_obj->id." updating biblio record $id");
520 my $session = OpenILS::Application::AppUtils->start_db_session();
522 warn "Retrieving biblio record from storage for update\n";
524 my $req1 = $session->request(
525 "open-ils.storage.direct.biblio.record_entry.batch.retrieve", $id );
526 my $biblio = $req1->gather(1);
528 warn "retrieved doc $id\n";
530 my $doc = XML::LibXML->new->parse_string($xml);
531 throw OpenSRF::EX::ERROR ("Invalid XML in record update: $xml") unless $doc;
533 $biblio->marc( entityize( $doc->documentElement->toString ) );
534 $biblio->editor( $user_obj->id );
535 $biblio->edit_date( 'now' );
537 warn "Sending updated doc $id to db with xml ".$biblio->marc. "\n";
539 my $req = $session->request(
540 "open-ils.storage.direct.biblio.record_entry.update", $biblio );
543 my $status = $req->recv();
544 if( !$status || $status->isa("Error") || ! $status->content) {
545 OpenILS::Application::AppUtils->rollback_db_session($session);
546 if($status->isa("Error")) { throw $status ($status); }
547 throw OpenSRF::EX::ERROR ("Error updating biblio record");
551 # Send the doc to the wormer for wormizing
552 warn "Starting worm session\n";
557 my $wreq = $session->request( "open-ils.worm.wormize.biblio", $id );
561 $w = $wreq->gather(1);
565 warn "wormizing failed, rolling back\n";
566 OpenILS::Application::AppUtils->rollback_db_session($session);
568 if($e) { throw $e ($e); }
569 throw OpenSRF::EX::ERROR ("Wormizing Failed for $id" );
572 warn "Committing db session...\n";
573 OpenILS::Application::AppUtils->commit_db_session( $session );
575 # $client->respond_complete($tree);
577 warn "Done wormizing\n";
580 #warn "Returning tree:\n";
591 __PACKAGE__->register_method(
592 method => "biblio_record_record_metadata",
593 api_name => "open-ils.cat.biblio.record.metadata.retrieve",
594 argc => 1, #(session_id, biblio_tree )
595 notes => "Walks the tree and commits any changed nodes " .
596 "adds any new nodes, and deletes any deleted nodes",
599 sub biblio_record_record_metadata {
600 my( $self, $client, $authtoken, $ids ) = @_;
602 return [] unless $ids and @$ids;
604 my $editor = new_editor(authtoken => $authtoken);
605 return $editor->event unless $editor->checkauth;
606 return $editor->event unless $editor->allowed('VIEW_USER');
611 return $editor->event unless
612 my $rec = $editor->retrieve_biblio_record_entry($_);
613 $rec->creator($editor->retrieve_actor_user($rec->creator));
614 $rec->editor($editor->retrieve_actor_user($rec->editor));
615 $rec->clear_marc; # slim the record down
616 push( @results, $rec );
624 __PACKAGE__->register_method(
625 method => "biblio_record_marc_cn",
626 api_name => "open-ils.cat.biblio.record.marc_cn.retrieve",
627 argc => 1, #(bib id )
630 sub biblio_record_marc_cn {
631 my( $self, $client, $id ) = @_;
633 my $session = OpenSRF::AppSession->create("open-ils.cstore");
635 ->request("open-ils.cstore.direct.biblio.record_entry.retrieve", $id )
639 my $doc = XML::LibXML->new->parse_string($marc);
640 $doc->documentElement->setNamespace( "http://www.loc.gov/MARC21/slim", "marc", 1 );
643 for my $tag ( qw/050 055 060 070 080 082 086 088 090 092 096 098 099/ ) {
644 my @node = $doc->findnodes("//marc:datafield[\@tag='$tag']");
646 my $cn = $x->findvalue("marc:subfield[\@code='a' or \@code='b']");
647 push @res, {$tag => $cn} if ($cn);
654 sub _get_id_by_userid {
659 my $session = OpenSRF::AppSession->create( "open-ils.cstore" );
660 my $request = $session->request(
661 "open-ils.cstore.direct.actor.user.search.atomic", { usrname => \@users } );
663 $request->wait_complete;
664 my $response = $request->recv();
665 if(!$request->complete) {
666 throw OpenSRF::EX::ERROR ("no response from cstore on user retrieve");
669 if(UNIVERSAL::isa( $response, "Error")){
670 throw $response ($response);
673 for my $u (@{$response->content}) {
679 $session->disconnect;
686 # commits metadata objects to the db
687 sub _update_record_metadata {
689 my ($session, @docs ) = @_;
691 for my $doc (@docs) {
693 my $user_obj = $doc->{user};
694 my $docid = $doc->{docid};
696 warn "Updating metata for doc $docid\n";
698 my $request = $session->request(
699 "open-ils.storage.direct.biblio.record_entry.retrieve", $docid );
700 my $record = $request->gather(1);
702 warn "retrieved record\n";
703 my ($id) = _get_id_by_userid($user_obj->usrname);
705 warn "got $id from _get_id_by_userid\n";
706 $record->editor($id);
708 warn "Grabbed the record, updating and moving on\n";
710 $request = $session->request(
711 "open-ils.storage.direct.biblio.record_entry.update", $record );
715 warn "committing metarecord update\n";
722 __PACKAGE__->register_method(
723 method => "orgs_for_title",
724 api_name => "open-ils.cat.actor.org_unit.retrieve_by_title"
728 my( $self, $client, $record_id ) = @_;
730 my $vols = $apputils->simple_scalar_request(
732 "open-ils.cstore.direct.asset.call_number.search.atomic",
733 { record => $record_id, deleted => 'f' });
735 my $orgs = { map {$_->owning_lib => 1 } @$vols };
736 return [ keys %$orgs ];
740 __PACKAGE__->register_method(
741 method => "retrieve_copies",
742 api_name => "open-ils.cat.asset.copy_tree.retrieve");
744 __PACKAGE__->register_method(
745 method => "retrieve_copies",
746 api_name => "open-ils.cat.asset.copy_tree.global.retrieve");
748 # user_session may be null/undef
749 sub retrieve_copies {
751 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
753 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
757 warn " $$ retrieving copy tree for orgs @org_ids and doc $docid at " . time() . "\n";
759 # grabbing copy trees should be available for everyone..
760 if(!@org_ids and $user_session) {
762 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
763 @org_ids = ($user_obj->home_ou);
766 if( $self->api_name =~ /global/ ) {
767 warn "performing global copy_tree search for $docid\n";
768 return _build_volume_list( { record => $docid, deleted => 'f' } );
773 for my $orgid (@org_ids) {
774 my $vols = _build_volume_list(
775 { record => $docid, owning_lib => $orgid, deleted => 'f' } );
776 warn "Volumes built for org $orgid\n";
777 push( @all_vols, @$vols );
780 warn " $$ Finished copy_tree at " . time() . "\n";
788 sub _build_volume_list {
789 my $search_hash = shift;
791 $search_hash->{deleted} = 'f';
792 my $e = new_editor();
794 my $vols = $e->search_asset_call_number($search_hash);
798 for my $volume (@$vols) {
800 my $copies = $e->search_asset_copy(
801 { call_number => $volume->id , deleted => 'f' });
803 $copies = [ sort { $a->barcode cmp $b->barcode } @$copies ];
805 for my $c (@$copies) {
806 if( $c->status == OILS_COPY_STATUS_CHECKED_OUT ) {
808 $e->search_action_circulation(
810 { target_copy => $c->id },
812 order_by => { circ => 'xact_start desc' },
821 $volume->copies($copies);
822 push( @volumes, $volume );
825 #$session->disconnect();
831 __PACKAGE__->register_method(
832 method => "fleshed_copy_update",
833 api_name => "open-ils.cat.asset.copy.fleshed.batch.update",);
835 __PACKAGE__->register_method(
836 method => "fleshed_copy_update",
837 api_name => "open-ils.cat.asset.copy.fleshed.batch.update.override",);
840 sub fleshed_copy_update {
841 my( $self, $conn, $auth, $copies, $delete_stats ) = @_;
842 return 1 unless ref $copies;
843 my( $reqr, $evt ) = $U->checkses($auth);
845 my $editor = new_editor(requestor => $reqr, xact => 1);
846 my $override = $self->api_name =~ /override/;
847 $evt = update_fleshed_copies($editor, $override, undef, $copies, $delete_stats);
849 $logger->info("fleshed copy update failed with event: ".JSON->perl2JSON($evt));
854 $logger->info("fleshed copy update successfully updated ".scalar(@$copies)." copies");
859 __PACKAGE__->register_method(
861 api_name => 'open-ils.cat.biblio.records.merge',
863 Merges a group of records
864 @param auth The login session key
865 @param master The id of the record all other r
866 ecords should be merged into
867 @param records Array of records to be merged into the master record
868 @return 1 on success, Event on error.
873 my( $self, $conn, $auth, $master, $records ) = @_;
874 my( $reqr, $evt ) = $U->checkses($auth);
876 my $editor = new_editor( requestor => $reqr, xact => 1 );
877 my $v = OpenILS::Application::Cat::Merge::merge_records($editor, $master, $records);
886 # ---------------------------------------------------------------------------
887 # ---------------------------------------------------------------------------
889 # returns true if the given title (id) has no un-deleted
892 my( $editor, $rid ) = @_;
894 return 0 if $rid == OILS_PRECAT_RECORD;
896 my $cnlist = $editor->search_asset_call_number(
897 { record => $rid, deleted => 'f' }, { idlist => 1 } );
898 return 1 unless @$cnlist;
900 for my $cn (@$cnlist) {
901 my $copylist = $editor->search_asset_copy(
903 { call_number => $cn, deleted => 'f' },
906 return 0 if @$copylist; # false if we find any copies
913 __PACKAGE__->register_method(
914 method => "fleshed_volume_update",
915 api_name => "open-ils.cat.asset.volume.fleshed.batch.update",);
917 __PACKAGE__->register_method(
918 method => "fleshed_volume_update",
919 api_name => "open-ils.cat.asset.volume.fleshed.batch.update.override",);
921 sub fleshed_volume_update {
922 my( $self, $conn, $auth, $volumes, $delete_stats ) = @_;
923 my( $reqr, $evt ) = $U->checkses($auth);
926 my $override = ($self->api_name =~ /override/);
927 my $editor = new_editor( requestor => $reqr, xact => 1 );
929 for my $vol (@$volumes) {
930 $logger->info("vol-update: investigating volume ".$vol->id);
932 $vol->editor($reqr->id);
933 $vol->edit_date('now');
935 my $copies = $vol->copies;
938 $vol->editor($editor->requestor->id);
939 $vol->edit_date('now');
941 if( $vol->isdeleted ) {
943 $logger->info("vol-update: deleting volume");
944 my $cs = $editor->search_asset_copy(
945 { call_number => $vol->id, deleted => 'f' } );
946 return OpenILS::Event->new(
947 'VOLUME_NOT_EMPTY', payload => $vol->id ) if @$cs;
950 return $editor->event unless
951 $editor->update_asset_call_number($vol);
954 } elsif( $vol->isnew ) {
955 $logger->info("vol-update: creating volume");
956 $evt = create_volume( $override, $editor, $vol );
959 } elsif( $vol->ischanged ) {
960 $logger->info("vol-update: update volume");
961 $evt = update_volume($vol, $editor);
965 # now update any attached copies
966 if( @$copies and !$vol->isdeleted ) {
967 $_->call_number($vol->id) for @$copies;
968 $evt = update_fleshed_copies( $editor, $override, $vol, $copies, $delete_stats );
974 return scalar(@$volumes);
982 my $vols = $editor->search_asset_call_number( {
983 owning_lib => $vol->owning_lib,
984 record => $vol->record,
985 label => $vol->label,
990 # There exists a different volume in the DB with the same properties
991 return OpenILS::Event->new('VOLUME_LABEL_EXISTS', payload => $vol->id)
992 if grep { $_->id ne $vol->id } @$vols;
994 return $editor->event unless $editor->update_asset_call_number($vol);
1001 my( $vol, $copy ) = @_;
1002 my $org = $vol->owning_lib;
1003 if( $vol->id == OILS_PRECAT_CALL_NUMBER ) {
1004 $org = ref($copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
1006 $logger->debug("using copy perm org $org");
1011 # this does the actual work
1012 sub update_fleshed_copies {
1013 my( $editor, $override, $vol, $copies, $delete_stats ) = @_;
1016 my $fetchvol = ($vol) ? 0 : 1;
1019 $cache{$vol->id} = $vol if $vol;
1021 for my $copy (@$copies) {
1023 my $copyid = $copy->id;
1024 $logger->info("vol-update: inspecting copy $copyid");
1026 if( !($vol = $cache{$copy->call_number}) ) {
1027 $vol = $cache{$copy->call_number} =
1028 $editor->retrieve_asset_call_number($copy->call_number);
1029 return $editor->event unless $vol;
1032 return $editor->event unless
1033 $editor->allowed('UPDATE_COPY', copy_perm_org($vol, $copy));
1035 $copy->editor($editor->requestor->id);
1036 $copy->edit_date('now');
1038 $copy->status( $copy->status->id ) if ref($copy->status);
1039 $copy->location( $copy->location->id ) if ref($copy->location);
1040 $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
1042 my $sc_entries = $copy->stat_cat_entries;
1043 $copy->clear_stat_cat_entries;
1045 if( $copy->isdeleted ) {
1046 $evt = delete_copy($editor, $override, $vol, $copy);
1047 return $evt if $evt;
1049 } elsif( $copy->isnew ) {
1050 $evt = create_copy( $editor, $vol, $copy );
1051 return $evt if $evt;
1053 } elsif( $copy->ischanged ) {
1055 $evt = update_copy( $editor, $override, $vol, $copy );
1056 return $evt if $evt;
1059 $copy->stat_cat_entries( $sc_entries );
1060 $evt = update_copy_stat_entries($editor, $copy, $delete_stats);
1061 return $evt if $evt;
1064 $logger->debug("vol-update: done updating copy batch");
1069 sub fix_copy_price {
1071 my $p = $copy->price || 0;
1075 my $d = $copy->deposit_amount || 0;
1077 $copy->deposit_amount($d);
1082 my( $editor, $override, $vol, $copy ) = @_;
1084 $logger->info("vol-update: updating copy ".$copy->id);
1085 my $orig_copy = $editor->retrieve_asset_copy($copy->id);
1086 my $orig_vol = $editor->retrieve_asset_call_number($copy->call_number);
1088 $copy->editor($editor->requestor->id);
1089 $copy->edit_date('now');
1091 $copy->age_protect( $copy->age_protect->id )
1092 if ref $copy->age_protect;
1094 fix_copy_price($copy);
1096 return $editor->event unless $editor->update_asset_copy($copy);
1097 return remove_empty_objects($editor, $override, $orig_vol);
1101 sub remove_empty_objects {
1102 my( $editor, $override, $vol ) = @_;
1103 if( title_is_empty($editor, $vol->record) ) {
1105 # disable the TITLE_LAST_COPY event for now
1109 # delete this volume if it's not already marked as deleted
1110 unless( $U->is_true($vol->deleted) || $vol->isdeleted ) {
1112 $vol->editor($editor->requestor->id);
1113 $vol->edit_date('now');
1114 $editor->update_asset_call_number($vol) or return $editor->event;
1117 # then delete the record this volume points to
1118 my $rec = $editor->retrieve_biblio_record_entry($vol->record)
1119 or return $editor->event;
1121 unless( $U->is_true($rec->deleted) ) {
1124 $editor->update_biblio_record_entry($rec) or return $editor->event;
1128 return OpenILS::Event->new('TITLE_LAST_COPY', payload => $vol->record );
1137 my( $editor, $override, $vol, $copy ) = @_;
1139 $logger->info("vol-update: deleting copy ".$copy->id);
1140 $copy->deleted('t');
1142 $copy->editor($editor->requestor->id);
1143 $copy->edit_date('now');
1144 $editor->update_asset_copy($copy) or return $editor->event;
1146 # Delete any open transits for this copy
1147 my $transits = $editor->search_action_transit_copy(
1148 { target_copy=>$copy->id, dest_recv_time => undef } );
1150 for my $t (@$transits) {
1151 $editor->delete_action_transit_copy($t)
1152 or return $editor->event;
1155 return remove_empty_objects($editor, $override, $vol);
1160 my( $editor, $vol, $copy ) = @_;
1162 my $existing = $editor->search_asset_copy(
1163 { barcode => $copy->barcode, deleted => 'f' } );
1165 return OpenILS::Event->new('ITEM_BARCODE_EXISTS') if @$existing;
1168 $copy->creator($editor->requestor->id);
1169 $copy->create_date('now');
1170 fix_copy_price($copy);
1172 $editor->create_asset_copy($copy) or return $editor->event;
1176 # if 'delete_stats' is true, the copy->stat_cat_entries data is
1177 # treated as the authoritative list for the copy. existing entries
1178 # that are not in said list will be deleted from the DB
1179 sub update_copy_stat_entries {
1180 my( $editor, $copy, $delete_stats ) = @_;
1182 return undef if $copy->isdeleted;
1183 return undef unless $copy->ischanged or $copy->isnew;
1186 my $entries = $copy->stat_cat_entries;
1188 if( $delete_stats ) {
1189 $entries = ($entries and @$entries) ? $entries : [];
1191 return undef unless ($entries and @$entries);
1194 my $maps = $editor->search_asset_stat_cat_entry_copy_map({owning_copy=>$copy->id});
1197 # if there is no stat cat entry on the copy who's id matches the
1198 # current map's id, remove the map from the database
1199 for my $map (@$maps) {
1200 if(! grep { $_->id == $map->stat_cat_entry } @$entries ) {
1202 $logger->info("copy update found stale ".
1203 "stat cat entry map ".$map->id. " on copy ".$copy->id);
1205 $editor->delete_asset_stat_cat_entry_copy_map($map)
1206 or return $editor->event;
1211 # go through the stat cat update/create process
1212 for my $entry (@$entries) {
1215 # if this link already exists in the DB, don't attempt to re-create it
1216 next if( grep{$_->stat_cat_entry == $entry->id} @$maps );
1218 my $new_map = Fieldmapper::asset::stat_cat_entry_copy_map->new();
1220 my $sc = ref($entry->stat_cat) ? $entry->stat_cat->id : $entry->stat_cat;
1222 $new_map->stat_cat( $sc );
1223 $new_map->stat_cat_entry( $entry->id );
1224 $new_map->owning_copy( $copy->id );
1226 $editor->create_asset_stat_cat_entry_copy_map($new_map)
1227 or return $editor->event;
1229 $logger->info("copy update created new stat cat entry map ".$editor->data);
1237 my( $override, $editor, $vol ) = @_;
1240 # first lets see if there are any collisions
1241 my $vols = $editor->search_asset_call_number( {
1242 owning_lib => $vol->owning_lib,
1243 record => $vol->record,
1244 label => $vol->label,
1252 $label = $vol->label;
1254 return OpenILS::Event->new(
1255 'VOLUME_LABEL_EXISTS', payload => $vol->id);
1259 # create a temp label so we can create the volume, then de-dup it
1260 $vol->label( '__SYSTEM_TMP_'.time) if $label;
1262 $vol->creator($editor->requestor->id);
1263 $vol->create_date('now');
1264 $vol->editor($editor->requestor->id);
1265 $vol->edit_date('now');
1268 $editor->create_asset_call_number($vol) or return $editor->event;
1271 # now restore the label and merge into the existing record
1272 $vol->label($label);
1274 OpenILS::Application::Cat::Merge::merge_volumes($editor, [$vol], $$vols[0]);
1275 return $evt if $evt;
1282 __PACKAGE__->register_method (
1283 method => 'batch_volume_transfer',
1284 api_name => 'open-ils.cat.asset.volume.batch.transfer',
1287 __PACKAGE__->register_method (
1288 method => 'batch_volume_transfer',
1289 api_name => 'open-ils.cat.asset.volume.batch.transfer.override',
1293 sub batch_volume_transfer {
1294 my( $self, $conn, $auth, $args ) = @_;
1297 my $rec = $$args{docid};
1298 my $o_lib = $$args{lib};
1299 my $vol_ids = $$args{volumes};
1301 my $override = 1 if $self->api_name =~ /override/;
1303 $logger->info("merge: transferring volumes to lib=$o_lib and record=$rec");
1305 my $e = new_editor(authtoken => $auth, xact =>1);
1306 return $e->event unless $e->checkauth;
1307 return $e->event unless $e->allowed('VOLUME_UPDATE', $o_lib);
1309 my $dorg = $e->retrieve_actor_org_unit($o_lib)
1310 or return $e->event;
1312 my $ou_type = $e->retrieve_actor_org_unit_type($dorg->ou_type)
1313 or return $e->event;
1315 return OpenILS::Event->new('ORG_CANNOT_HAVE_VOLS')
1316 unless $U->is_true($ou_type->can_have_vols);
1318 my $vols = $e->batch_retrieve_asset_call_number($vol_ids);
1321 for my $vol (@$vols) {
1323 # if we've already looked at this volume, go to the next
1324 next if !$vol or grep { $vol->id == $_ } @seen;
1326 # grab all of the volumes in the list that have
1327 # the same label so they can be merged
1328 my @all = grep { $_->label eq $vol->label } @$vols;
1330 # take note of the fact that we've looked at this set of volumes
1331 push( @seen, $_->id ) for @all;
1333 # for each volume, see if there are any copies that have a
1334 # remote circ_lib (circ_lib != vol->owning_lib and != $o_lib ).
1336 unless( $override ) {
1339 $logger->debug("merge: searching for copies with remote circ_lib for volume ".$v->id);
1341 call_number => $v->id,
1342 circ_lib => { "not in" => [ $o_lib, $v->owning_lib ] },
1346 my $copies = $e->search_asset_copy($args, {idlist=>1});
1348 # if the copy's circ_lib matches the destination lib,
1350 return OpenILS::Event->new('COPY_REMOTE_CIRC_LIB') if @$copies;
1354 # see if there is a volume at the destination lib that
1355 # already has the requested label
1356 my $existing_vol = $e->search_asset_call_number(
1358 label => $vol->label,
1360 owning_lib =>$o_lib,
1365 if( $existing_vol ) {
1367 if( grep { $_->id == $existing_vol->id } @all ) {
1368 # this volume is already accounted for in our list of volumes to merge
1369 $existing_vol = undef;
1372 # this volume exists on the destination record/owning_lib and must
1373 # be used as the destination for merging
1374 $logger->debug("merge: volume already exists at destination record: ".
1375 $existing_vol->id.' : '.$existing_vol->label) if $existing_vol;
1379 if( @all > 1 || $existing_vol ) {
1380 $logger->info("merge: found collisions in volume transfer");
1381 my @args = ($e, \@all);
1382 @args = ($e, \@all, $existing_vol) if $existing_vol;
1383 ($vol, $evt) = OpenILS::Application::Cat::Merge::merge_volumes(@args);
1384 return $evt if $evt;
1387 if( !$existing_vol ) {
1389 $vol->owning_lib($o_lib);
1391 $vol->editor($e->requestor->id);
1392 $vol->edit_date('now');
1394 $logger->info("merge: updating volume ".$vol->id);
1395 $e->update_asset_call_number($vol) or return $e->event;
1398 $logger->info("merge: bypassing volume update because existing volume used as target");
1401 # regardless of what volume was used as the destination,
1402 # update any copies that have moved over to the new lib
1403 my $copies = $e->search_asset_copy({call_number=>$vol->id, deleted => 'f'});
1405 # update circ lib on the copies - make this a method flag?
1406 for my $copy (@$copies) {
1407 next if $copy->circ_lib == $o_lib;
1408 $logger->info("merge: transfer moving circ lib on copy ".$copy->id);
1409 $copy->circ_lib($o_lib);
1410 $copy->editor($e->requestor->id);
1411 $copy->edit_date('now');
1412 $e->update_asset_copy($copy) or return $e->event;
1415 # Now see if any empty records need to be deleted after all of this
1417 $evt = remove_empty_objects($e, $override, $_);
1418 return $evt if $evt;
1422 $logger->info("merge: transfer succeeded");