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;
15 use Unicode::Normalize;
17 use OpenILS::Utils::FlatXML;
18 use OpenILS::Utils::CStoreEditor q/:funcs/;
19 use OpenILS::Utils::Editor;
21 use OpenSRF::Utils::SettingsClient;
22 use OpenSRF::Utils::Logger qw($logger);
23 use OpenSRF::AppSession;
25 my $apputils = "OpenILS::Application::AppUtils";
27 my $utils = "OpenILS::Application::Cat::Utils";
28 my $U = "OpenILS::Application::AppUtils";
36 my $form = shift || "";
44 $stuff =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
48 __PACKAGE__->register_method(
49 method => "retrieve_marc_template",
50 api_name => "open-ils.cat.biblio.marc_template.retrieve",
52 Returns a MARC 'record tree' based on a set of pre-defined templates.
53 Templates include : book
56 sub retrieve_marc_template {
57 my( $self, $client, $type ) = @_;
59 return $marctemplates{$type} if defined($marctemplates{$type});
60 $marctemplates{$type} = _load_marc_template($type);
61 return $marctemplates{$type};
64 sub _load_marc_template {
67 if(!$conf) { $conf = OpenSRF::Utils::SettingsClient->new; }
69 my $template = $conf->config_value(
70 "apps", "open-ils.cat","app_settings", "marctemplates", $type );
71 warn "Opening template file $template\n";
73 open( F, $template ) or
74 throw OpenSRF::EX::ERROR ("Unable to open MARC template file: $template : $@");
78 my $xml = join('', @xml);
80 return XML::LibXML->new->parse_string($xml)->documentElement->toString;
84 sub bib_source_from_name {
86 $logger->debug("searching for bib source: $name");
88 $__bib_sources = new_editor()->retrieve_all_config_bib_source()
89 unless $__bib_sources;
91 my ($s) = grep { lc($_->source) eq lc($name) } @$__bib_sources;
99 __PACKAGE__->register_method(
100 method => "create_record_xml",
101 api_name => "open-ils.cat.biblio.record.xml.create.override",
102 signature => q/@see open-ils.cat.biblio.record.xml.create/);
104 __PACKAGE__->register_method(
105 method => "create_record_xml",
106 api_name => "open-ils.cat.biblio.record.xml.create",
108 Inserts a new biblio with the given XML
112 sub create_record_xml {
113 my( $self, $client, $login, $xml, $source ) = @_;
115 my $override = 1 if $self->api_name =~ /override/;
117 my( $user_obj, $evt ) = $U->checksesperm($login, 'CREATE_MARC');
120 $logger->activity("user ".$user_obj->id." creating new MARC record");
122 my $meth = $self->method_lookup("open-ils.cat.biblio.record.xml.import");
124 $meth = $self->method_lookup(
125 "open-ils.cat.biblio.record.xml.import.override") if $override;
127 my ($s) = $meth->run($login, $xml, $source);
133 __PACKAGE__->register_method(
134 method => "biblio_record_replace_marc",
135 api_name => "open-ils.cat.biblio.record.xml.update",
138 Updates the XML for a given biblio record.
139 This does not change any other aspect of the record entry
140 exception the XML, the editor, and the edit date.
141 @return The update record object
145 __PACKAGE__->register_method(
146 method => 'biblio_record_replace_marc',
147 api_name => 'open-ils.cat.biblio.record.marc.replace',
149 @param auth The authtoken
150 @param recid The record whose MARC we're replacing
151 @param newxml The new xml to use
155 __PACKAGE__->register_method(
156 method => 'biblio_record_replace_marc',
157 api_name => 'open-ils.cat.biblio.record.marc.replace.override',
158 signature => q/@see open-ils.cat.biblio.record.marc.replace/
161 sub biblio_record_replace_marc {
162 my( $self, $conn, $auth, $recid, $newxml, $source ) = @_;
164 my $e = OpenILS::Utils::Editor->new(authtoken=>$auth, xact=>1);
166 return $e->event unless $e->checkauth;
167 return $e->event unless $e->allowed('CREATE_MARC');
169 my $rec = $e->retrieve_biblio_record_entry($recid)
172 my $fixtcn = 1 if $self->api_name =~ /replace/o;
174 # See if there is a different record in the database that has our TCN value
175 # If we're not updating the TCN, all we care about it the marcdoc
176 my $override = $self->api_name =~ /override/;
178 my $storage = OpenSRF::AppSession->create('open-ils.storage');
180 my( $tcn, $tsource, $marcdoc, $evt) =
181 _find_tcn_info($e->session, $newxml, $override, $recid);
186 $rec->tcn_value($tcn);
187 $rec->tcn_source($tsource);
190 $rec->source(bib_source_from_name($source)) if $source;
191 $rec->editor($e->requestor->id);
192 $rec->edit_date('now');
193 $rec->marc( entityize( $marcdoc->documentElement->toString ) );
195 $logger->activity("user ".$e->requestor->id." replacing MARC for record $recid");
197 $e->update_biblio_record_entry($rec) or return $e->event;
198 $e->request('open-ils.worm.wormize.biblio', $recid) or return $e->event;
207 __PACKAGE__->register_method(
208 method => "biblio_record_xml_import",
209 api_name => "open-ils.cat.biblio.record.xml.import.override",
210 signature => q/@see open-ils.cat.biblio.record.xml.import/);
212 __PACKAGE__->register_method(
213 method => "biblio_record_xml_import",
214 api_name => "open-ils.cat.biblio.record.xml.import",
215 notes => <<" NOTES");
216 Takes a marcxml record and imports the record into the database. In this
217 case, the marcxml record is assumed to be a complete record (i.e. valid
218 MARC). The title control number is taken from (whichever comes first)
219 tags 001, 039[ab], 020a, 022a, 010, 035a and whichever does not already exist
221 user_session must have IMPORT_MARC permissions
225 sub biblio_record_xml_import {
226 my( $self, $client, $authtoken, $xml, $source) = @_;
229 # XXX Make the source the ID from config.bib_source
231 my $override = 1 if $self->api_name =~ /override/;
233 my( $tcn, $tcn_source, $marcdoc );
234 my( $requestor, $evt ) = $U->checksesperm($authtoken, 'IMPORT_MARC');
237 my $session = $apputils->start_db_session();
239 ( $tcn, $tcn_source, $marcdoc, $evt ) = _find_tcn_info($session, $xml, $override);
242 $logger->activity("user ".$requestor->id.
243 " creating new biblio entry with tcn=$tcn and tcn_source $tcn_source");
245 my $record = Fieldmapper::biblio::record_entry->new;
247 $record->source(bib_source_from_name($source)) if $source;
248 $record->tcn_source($tcn_source);
249 $record->tcn_value($tcn);
250 $record->creator($requestor->id);
251 $record->editor($requestor->id);
252 $record->create_date('now');
253 $record->edit_date('now');
254 $record->marc( entityize( $marcdoc->documentElement->toString ) );
256 my $id = $session->request(
257 "open-ils.storage.direct.biblio.record_entry.create", $record )->gather(1);
259 return $U->DB_UPDATE_FAILED($record) unless $id;
262 $logger->info("marc create/import created new record $id");
264 $apputils->commit_db_session($session);
266 $logger->debug("Sending record off to be wormized");
268 my $stat = $U->storagereq( 'open-ils.worm.wormize.biblio', $id );
269 throw OpenSRF::EX::ERROR
270 ("Unable to wormize imported record") unless $stat;
279 my $override = shift;
280 my $existing_rec = shift || 0;
283 my $marcxml = XML::LibXML->new->parse_string( $xml );
284 $marcxml->documentElement->setNamespace(
285 "http://www.loc.gov/MARC21/slim", "marc", 1 );
287 my $xpath = '//marc:controlfield[@tag="001"]';
288 my $tcn = $marcxml->documentElement->findvalue($xpath);
289 $logger->info("biblio import located 001 (tcn) value of $tcn");
291 $xpath = '//marc:controlfield[@tag="003"]';
292 my $tcn_source = $marcxml->documentElement->findvalue($xpath) || "System Local";
294 if(my $rec = _tcn_exists($session, $tcn, $tcn_source, $existing_rec) ) {
297 $tcn = find_free_tcn( $marcxml, $session, $existing_rec );
299 # if we're overriding, try to find a different TCN to use
302 $logger->activity("tcn value $tcn already exists, attempting to override");
310 'OPEN_TCN_NOT_FOUND',
311 payload => $marcxml->toString())
317 $logger->warn("tcn value $origtcn already exists in import/create");
319 # otherwise, return event
325 'TCN_EXISTS', payload => {
335 return ($tcn, $tcn_source, $marcxml);
342 my $existing_rec = shift;
346 my $xpath = '//marc:datafield[@tag="039"]/subfield[@code="a"]';
347 my ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
348 $xpath = '//marc:datafield[@tag="039"]/subfield[@code="b"]';
349 my $tcn_source = $marcxml->documentElement->findvalue($xpath) || "System Local";
351 if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {
359 $xpath = '//marc:datafield[@tag="020"]/subfield[@code="a"]';
360 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
361 $tcn_source = "ISBN";
362 if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
366 $xpath = '//marc:datafield[@tag="022"]/subfield[@code="a"]';
367 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
368 $tcn_source = "ISSN";
369 if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
373 $xpath = '//marc:datafield[@tag="010"]';
374 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
375 $tcn_source = "LCCN";
376 if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
380 $xpath = '//marc:datafield[@tag="035"]/subfield[@code="a"]';
381 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
382 $tcn_source = "System Legacy";
383 if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
386 $marcxml->documentElement->removeChild(
387 $marcxml->documentElement->findnodes( '//datafield[@tag="035"]' )
392 return undef unless $tcn;
395 my $df = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'datafield');
396 $df->setAttribute( tag => '039' );
397 $df->setAttribute( ind1 => ' ' );
398 $df->setAttribute( ind2 => ' ' );
399 $marcxml->documentElement->appendChild( $df );
401 my $sfa = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'subfield');
402 $sfa->setAttribute( code => 'a' );
403 $sfa->appendChild( $marcxml->createTextNode( $tcn ) );
404 $df->appendChild( $sfa );
406 my $sfb = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'subfield');
407 $sfb->setAttribute( code => 'b' );
408 $sfb->appendChild( $marcxml->createTextNode( $tcn_source ) );
409 $df->appendChild( $sfb );
421 my $existing_rec = shift || 0;
423 if(!$tcn) {return 0;}
425 $logger->debug("tcn_exists search for tcn $tcn and source $source and id $existing_rec");
427 # XXX why does the source matter?
428 # my $req = $session->request(
429 # { tcn_value => $tcn, tcn_source => $source, deleted => 'f' } );
431 my $req = $session->request(
432 "open-ils.storage.id_list.biblio.record_entry.search_where.atomic",
433 { tcn_value => $tcn, deleted => 'f', id => {'!=' => $existing_rec} } );
435 my $recs = $req->gather(1);
437 if($recs and $recs->[0]) {
438 $logger->debug("_tcn_exists is true for tcn : $tcn ($source)");
442 $logger->debug("_tcn_exists is false for tcn : $tcn ($source)");
449 # XXX deprecated. Remove me.
453 __PACKAGE__->register_method(
454 method => "biblio_record_tree_retrieve",
455 api_name => "open-ils.cat.biblio.record.tree.retrieve",
458 sub biblio_record_tree_retrieve {
460 my( $self, $client, $recordid ) = @_;
462 my $name = "open-ils.storage.direct.biblio.record_entry.retrieve";
463 my $session = OpenSRF::AppSession->create( "open-ils.storage" );
464 my $request = $session->request( $name, $recordid );
465 my $marcxml = $request->gather(1);
468 throw OpenSRF::EX::ERROR
469 ("No record in database with id $recordid");
472 $session->disconnect();
475 warn "turning into nodeset\n";
476 my $nodes = OpenILS::Utils::FlatXML->new()->xml_to_nodeset( $marcxml->marc );
477 warn "turning nodeset into tree\n";
478 my $tree = $utils->nodeset2tree( $nodes->nodeset );
480 $tree->owner_doc( $marcxml->id() );
482 warn "returning tree\n";
490 __PACKAGE__->register_method(
491 method => "biblio_record_xml_update",
492 api_name => "open-ils.cat.biblio.record.xml.update",
493 argc => 3, #(session_id, biblio_tree )
494 notes => <<' NOTES');
495 Updates the XML of a biblio record entry
496 @param authtoken The session token for the staff updating the record
497 @param docID The record entry ID to update
498 @param xml The new MARCXML record
501 sub biblio_record_xml_update {
503 my( $self, $client, $user_session, $id, $xml ) = @_;
505 my $user_obj = $apputils->check_user_session($user_session);
507 if($apputils->check_user_perms(
508 $user_obj->id, $user_obj->home_ou, "UPDATE_MARC")) {
509 return OpenILS::Perm->new("UPDATE_MARC");
512 $logger->activity("user ".$user_obj->id." updating biblio record $id");
515 my $session = OpenILS::Application::AppUtils->start_db_session();
517 warn "Retrieving biblio record from storage for update\n";
519 my $req1 = $session->request(
520 "open-ils.storage.direct.biblio.record_entry.batch.retrieve", $id );
521 my $biblio = $req1->gather(1);
523 warn "retrieved doc $id\n";
525 my $doc = XML::LibXML->new->parse_string($xml);
526 throw OpenSRF::EX::ERROR ("Invalid XML in record update: $xml") unless $doc;
528 $biblio->marc( entityize( $doc->documentElement->toString ) );
529 $biblio->editor( $user_obj->id );
530 $biblio->edit_date( 'now' );
532 warn "Sending updated doc $id to db with xml ".$biblio->marc. "\n";
534 my $req = $session->request(
535 "open-ils.storage.direct.biblio.record_entry.update", $biblio );
538 my $status = $req->recv();
539 if( !$status || $status->isa("Error") || ! $status->content) {
540 OpenILS::Application::AppUtils->rollback_db_session($session);
541 if($status->isa("Error")) { throw $status ($status); }
542 throw OpenSRF::EX::ERROR ("Error updating biblio record");
546 # Send the doc to the wormer for wormizing
547 warn "Starting worm session\n";
552 my $wreq = $session->request( "open-ils.worm.wormize.biblio", $id );
556 $w = $wreq->gather(1);
560 warn "wormizing failed, rolling back\n";
561 OpenILS::Application::AppUtils->rollback_db_session($session);
563 if($e) { throw $e ($e); }
564 throw OpenSRF::EX::ERROR ("Wormizing Failed for $id" );
567 warn "Committing db session...\n";
568 OpenILS::Application::AppUtils->commit_db_session( $session );
570 # $client->respond_complete($tree);
572 warn "Done wormizing\n";
575 #warn "Returning tree:\n";
586 __PACKAGE__->register_method(
587 method => "biblio_record_record_metadata",
588 api_name => "open-ils.cat.biblio.record.metadata.retrieve",
589 argc => 1, #(session_id, biblio_tree )
590 notes => "Walks the tree and commits any changed nodes " .
591 "adds any new nodes, and deletes any deleted nodes",
594 sub biblio_record_record_metadata {
595 my( $self, $client, $authtoken, $ids ) = @_;
597 return [] unless $ids and @$ids;
599 my $editor = new_editor(authtoken => $authtoken);
600 return $editor->event unless $editor->checkauth;
601 return $editor->event unless $editor->allowed('VIEW_USER');
606 return $editor->event unless
607 my $rec = $editor->retrieve_biblio_record_entry($_);
608 $rec->creator($editor->retrieve_actor_user($rec->creator));
609 $rec->editor($editor->retrieve_actor_user($rec->editor));
610 $rec->clear_marc; # slim the record down
611 push( @results, $rec );
619 __PACKAGE__->register_method(
620 method => "biblio_record_marc_cn",
621 api_name => "open-ils.cat.biblio.record.marc_cn.retrieve",
622 argc => 1, #(bib id )
625 sub biblio_record_marc_cn {
626 my( $self, $client, $id ) = @_;
628 my $session = OpenSRF::AppSession->create("open-ils.cstore");
630 ->request("open-ils.cstore.direct.biblio.record_entry.retrieve", $id )
634 my $doc = XML::LibXML->new->parse_string($marc);
635 $doc->documentElement->setNamespace( "http://www.loc.gov/MARC21/slim", "marc", 1 );
638 for my $tag ( qw/050 055 060 070 080 082 086 088 090 092 096 098 099/ ) {
639 my @node = $doc->findnodes("//marc:datafield[\@tag='$tag']");
641 my $cn = $x->findvalue("marc:subfield[\@code='a' or \@code='b']");
642 push @res, {$tag => $cn} if ($cn);
649 sub _get_id_by_userid {
654 my $session = OpenSRF::AppSession->create( "open-ils.cstore" );
655 my $request = $session->request(
656 "open-ils.cstore.direct.actor.user.search.atomic", { usrname => \@users } );
658 $request->wait_complete;
659 my $response = $request->recv();
660 if(!$request->complete) {
661 throw OpenSRF::EX::ERROR ("no response from cstore on user retrieve");
664 if(UNIVERSAL::isa( $response, "Error")){
665 throw $response ($response);
668 for my $u (@{$response->content}) {
674 $session->disconnect;
681 # commits metadata objects to the db
682 sub _update_record_metadata {
684 my ($session, @docs ) = @_;
686 for my $doc (@docs) {
688 my $user_obj = $doc->{user};
689 my $docid = $doc->{docid};
691 warn "Updating metata for doc $docid\n";
693 my $request = $session->request(
694 "open-ils.storage.direct.biblio.record_entry.retrieve", $docid );
695 my $record = $request->gather(1);
697 warn "retrieved record\n";
698 my ($id) = _get_id_by_userid($user_obj->usrname);
700 warn "got $id from _get_id_by_userid\n";
701 $record->editor($id);
703 warn "Grabbed the record, updating and moving on\n";
705 $request = $session->request(
706 "open-ils.storage.direct.biblio.record_entry.update", $record );
710 warn "committing metarecord update\n";
717 __PACKAGE__->register_method(
718 method => "orgs_for_title",
719 api_name => "open-ils.cat.actor.org_unit.retrieve_by_title"
723 my( $self, $client, $record_id ) = @_;
725 my $vols = $apputils->simple_scalar_request(
727 "open-ils.cstore.direct.asset.call_number.search.atomic",
728 { record => $record_id, deleted => 'f' });
730 my $orgs = { map {$_->owning_lib => 1 } @$vols };
731 return [ keys %$orgs ];
735 __PACKAGE__->register_method(
736 method => "retrieve_copies",
737 api_name => "open-ils.cat.asset.copy_tree.retrieve");
739 __PACKAGE__->register_method(
740 method => "retrieve_copies",
741 api_name => "open-ils.cat.asset.copy_tree.global.retrieve");
743 # user_session may be null/undef
744 sub retrieve_copies {
746 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
748 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
752 warn " $$ retrieving copy tree for orgs @org_ids and doc $docid at " . time() . "\n";
754 # grabbing copy trees should be available for everyone..
755 if(!@org_ids and $user_session) {
757 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
758 @org_ids = ($user_obj->home_ou);
761 if( $self->api_name =~ /global/ ) {
762 warn "performing global copy_tree search for $docid\n";
763 return _build_volume_list( { record => $docid } );
768 for my $orgid (@org_ids) {
769 my $vols = _build_volume_list(
770 { record => $docid, owning_lib => $orgid } );
771 warn "Volumes built for org $orgid\n";
772 push( @all_vols, @$vols );
775 warn " $$ Finished copy_tree at " . time() . "\n";
783 sub _build_volume_list {
784 my $search_hash = shift;
786 $search_hash->{deleted} = 'f';
788 my $session = OpenSRF::AppSession->create( "open-ils.cstore" );
791 my $request = $session->request(
792 "open-ils.cstore.direct.asset.call_number.search.atomic", $search_hash );
793 #"open-ils.storage.direct.asset.call_number.search.atomic", $search_hash );
795 my $vols = $request->gather(1);
798 for my $volume (@$vols) {
800 warn "Grabbing copies for volume: " . $volume->id . "\n";
801 my $creq = $session->request(
802 "open-ils.cstore.direct.asset.copy.search.atomic",
803 { call_number => $volume->id , deleted => 'f' });
804 #"open-ils.storage.direct.asset.copy.search.call_number.atomic", $volume->id );
806 my $copies = $creq->gather(1);
808 $copies = [ sort { $a->barcode cmp $b->barcode } @$copies ];
810 $volume->copies($copies);
812 push( @volumes, $volume );
816 $session->disconnect();
822 __PACKAGE__->register_method(
823 method => "fleshed_copy_update",
824 api_name => "open-ils.cat.asset.copy.fleshed.batch.update",);
826 __PACKAGE__->register_method(
827 method => "fleshed_copy_update",
828 api_name => "open-ils.cat.asset.copy.fleshed.batch.update.override",);
831 sub fleshed_copy_update {
832 my( $self, $conn, $auth, $copies, $delete_stats ) = @_;
833 return 1 unless ref $copies;
834 my( $reqr, $evt ) = $U->checkses($auth);
836 my $editor = new_editor(requestor => $reqr, xact => 1);
837 my $override = $self->api_name =~ /override/;
838 $evt = update_fleshed_copies($editor, $override, undef, $copies, $delete_stats);
841 $logger->info("fleshed copy update successfully updated ".scalar(@$copies)." copies");
846 __PACKAGE__->register_method(
848 api_name => 'open-ils.cat.biblio.records.merge',
850 Merges a group of records
851 @param auth The login session key
852 @param master The id of the record all other r
853 ecords should be merged into
854 @param records Array of records to be merged into the master record
855 @return 1 on success, Event on error.
860 my( $self, $conn, $auth, $master, $records ) = @_;
861 my( $reqr, $evt ) = $U->checkses($auth);
863 my $editor = new_editor( requestor => $reqr, xact => 1 );
864 my $v = OpenILS::Application::Cat::Merge::merge_records($editor, $master, $records);
873 # ---------------------------------------------------------------------------
874 # ---------------------------------------------------------------------------
876 # returns true if the given title (id) has no un-deleted
879 my( $editor, $rid ) = @_;
881 my $cnlist = $editor->search_asset_call_number(
882 { record => $rid, deleted => 'f' }, { idlist => 1 } );
883 return 1 unless @$cnlist;
885 for my $cn (@$cnlist) {
886 my $copylist = $editor->search_asset_copy(
887 { call_number => $cn, deleted => 'f' }, { idlist => 1 });
888 return 0 if @$copylist; # false if we find any copies
895 __PACKAGE__->register_method(
896 method => "fleshed_volume_update",
897 api_name => "open-ils.cat.asset.volume.fleshed.batch.update",);
899 __PACKAGE__->register_method(
900 method => "fleshed_volume_update",
901 api_name => "open-ils.cat.asset.volume.fleshed.batch.update.override",);
903 sub fleshed_volume_update {
904 my( $self, $conn, $auth, $volumes, $delete_stats ) = @_;
905 my( $reqr, $evt ) = $U->checkses($auth);
908 my $override = ($self->api_name =~ /override/);
909 my $editor = new_editor( requestor => $reqr, xact => 1 );
911 for my $vol (@$volumes) {
912 $logger->info("vol-update: investigating volume ".$vol->id);
914 $vol->editor($reqr->id);
915 $vol->edit_date('now');
917 my $copies = $vol->copies;
920 if( $vol->isdeleted ) {
922 $logger->info("vol-update: deleting volume");
923 my $cs = $editor->search_asset_copy(
924 { call_number => $vol->id, deleted => 'f' } );
925 return OpenILS::Event->new(
926 'VOLUME_NOT_EMPTY', payload => $vol->id ) if @$cs;
929 return $editor->event unless
930 $editor->update_asset_call_number($vol);
933 } elsif( $vol->isnew ) {
934 $logger->info("vol-update: creating volume");
935 $evt = create_volume( $override, $editor, $vol );
938 } elsif( $vol->ischanged ) {
939 $logger->info("vol-update: update volume");
940 return $editor->event unless
941 $editor->update_asset_call_number($vol);
945 # now update any attached copies
946 if( @$copies and !$vol->isdeleted ) {
947 $_->call_number($vol->id) for @$copies;
948 $evt = update_fleshed_copies( $editor, $override, $vol, $copies, $delete_stats );
954 return scalar(@$volumes);
958 # this does the actual work
959 sub update_fleshed_copies {
960 my( $editor, $override, $vol, $copies, $delete_stats ) = @_;
963 my $fetchvol = ($vol) ? 0 : 1;
966 $cache{$vol->id} = $vol if $vol;
968 for my $copy (@$copies) {
970 my $copyid = $copy->id;
971 $logger->info("vol-update: inspecting copy $copyid");
973 if( !($vol = $cache{$copy->call_number}) ) {
974 $vol = $cache{$copy->call_number} =
975 $editor->retrieve_asset_call_number($copy->call_number);
976 return $editor->event unless $vol;
979 $copy->editor($editor->requestor->id);
980 $copy->edit_date('now');
982 $copy->status( $copy->status->id ) if ref($copy->status);
983 $copy->location( $copy->location->id ) if ref($copy->location);
984 $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
986 my $sc_entries = $copy->stat_cat_entries;
987 $copy->clear_stat_cat_entries;
989 if( $copy->isdeleted ) {
990 $evt = delete_copy($editor, $override, $vol, $copy);
993 } elsif( $copy->isnew ) {
994 $evt = create_copy( $editor, $vol, $copy );
997 } elsif( $copy->ischanged ) {
999 $logger->info("vol-update: updating copy $copyid");
1000 return $editor->event unless
1001 $editor->update_asset_copy(
1002 $copy, {checkperm=>1, permorg=>$vol->owning_lib});
1003 return $evt if $evt;
1006 $copy->stat_cat_entries( $sc_entries );
1007 $evt = update_copy_stat_entries($editor, $copy, $delete_stats);
1008 return $evt if $evt;
1011 $logger->debug("vol-update: done updating copy batch");
1017 my( $editor, $override, $vol, $copy ) = @_;
1019 $logger->info("vol-update: deleting copy ".$copy->id);
1020 $copy->deleted('t');
1022 $editor->update_asset_copy(
1023 $copy, {checkperm=>1, permorg=>$vol->owning_lib})
1024 or return $editor->event;
1026 if( title_is_empty($editor, $vol->record) ) {
1030 # delete this volume if it's not already marked as deleted
1031 unless( $U->is_true($vol->deleted) || $vol->isdeleted ) {
1033 $editor->update_asset_call_number($vol, {checkperm=>0})
1034 or return $editor->event;
1037 # then delete the record this volume points to
1038 my $rec = $editor->retrieve_biblio_record_entry($vol->record)
1039 or return $editor->event;
1041 unless( $U->is_true($rec->deleted) ) {
1044 $editor->update_biblio_record_entry($rec, {checkperm=>0})
1045 or return $editor->event;
1049 return OpenILS::Event->new('TITLE_LAST_COPY');
1057 my( $editor, $vol, $copy ) = @_;
1059 my $existing = $editor->search_asset_copy(
1060 { barcode => $copy->barcode } );
1062 return OpenILS::Event->new('ITEM_BARCODE_EXISTS') if @$existing;
1065 $copy->creator($editor->requestor->id);
1066 $copy->create_date('now');
1068 $editor->create_asset_copy(
1069 $copy, {checkperm=>1, permorg=>$vol->owning_lib})
1070 or return $editor->event;
1075 # if 'delete_stats' is true, the copy->stat_cat_entries data is
1076 # treated as the authoritative list for the copy. existing entries
1077 # that are not in said list will be deleted from the DB
1078 sub update_copy_stat_entries {
1079 my( $editor, $copy, $delete_stats ) = @_;
1082 my $entries = $copy->stat_cat_entries;
1084 if( $delete_stats ) {
1085 $entries = ($entries and @$entries) ? $entries : [];
1087 return undef unless ($entries and @$entries);
1090 my $maps = $editor->search_asset_stat_cat_entry_copy_map({owning_copy=>$copy->id});
1093 # if there is no stat cat entry on the copy who's id matches the
1094 # current map's id, remove the map from the database
1095 for my $map (@$maps) {
1096 if(! grep { $_->id == $map->stat_cat_entry } @$entries ) {
1098 $logger->info("copy update found stale ".
1099 "stat cat entry map ".$map->id. " on copy ".$copy->id);
1101 $editor->delete_asset_stat_cat_entry_copy_map($map)
1102 or return $editor->event;
1107 # go through the stat cat update/create process
1108 for my $entry (@$entries) {
1111 # if this link already exists in the DB, don't attempt to re-create it
1112 next if( grep{$_->stat_cat_entry == $entry->id} @$maps );
1114 my $new_map = Fieldmapper::asset::stat_cat_entry_copy_map->new();
1116 $new_map->stat_cat( $entry->stat_cat );
1117 $new_map->stat_cat_entry( $entry->id );
1118 $new_map->owning_copy( $copy->id );
1120 $editor->create_asset_stat_cat_entry_copy_map($new_map)
1121 or return $editor->event;
1123 $logger->info("copy update created new stat cat entry map ".$editor->data);
1131 my( $override, $editor, $vol ) = @_;
1135 # first lets see if there are any collisions
1136 my $vols = $editor->search_asset_call_number( {
1137 owning_lib => $vol->owning_lib,
1138 record => $vol->record,
1139 label => $vol->label,
1147 $label = $vol->label;
1149 return OpenILS::Event->new(
1150 'VOLUME_LABEL_EXISTS', payload => $vol->id);
1154 # create a temp label so we can create the volume, then de-dup it
1155 $vol->label( '__SYSTEM_TMP_'.time) if $label;
1157 $vol->creator($editor->requestor->id);
1158 $vol->create_date('now');
1161 $editor->create_asset_call_number($vol) or return $editor->event;
1164 # now restore the label and merge into the existing record
1165 $vol->label($label);
1167 OpenILS::Application::Cat::Merge::merge_volumes($editor, [$vol], $$vols[0]);
1168 return $evt if $evt;
1175 __PACKAGE__->register_method (
1176 method => 'batch_volume_transfer',
1177 api_name => 'open-ils.cat.asset.volume.batch.transfer',
1180 __PACKAGE__->register_method (
1181 method => 'batch_volume_transfer',
1182 api_name => 'open-ils.cat.asset.volume.batch.transfer.override',
1186 sub batch_volume_transfer {
1187 my( $self, $conn, $auth, $args ) = @_;
1190 my $rec = $$args{docid};
1191 my $o_lib = $$args{lib};
1192 my $vol_ids = $$args{volumes};
1194 $logger->info("merge: transferring volumes to lib=$o_lib and record=$rec");
1196 my $e = new_editor(authtoken => $auth, xact =>1);
1197 return $e->event unless $e->checkauth;
1198 return $e->event unless $e->allowed('VOLUME_UPDATE');
1200 my $dorg = $e->retrieve_actor_org_unit($o_lib)
1201 or return $e->event;
1203 my $ou_type = $e->retrieve_actor_org_unit_type($dorg->ou_type)
1204 or return $e->event;
1206 return OpenILS::Event->new('ORG_CANNOT_HAVE_VOLS')
1207 unless $U->is_true($ou_type->can_have_vols);
1209 my $vols = $e->batch_retrieve_asset_call_number($vol_ids);
1212 for my $vol (@$vols) {
1214 # if we've already looked at this volume, go to the next
1215 next if !$vol or grep { $vol->id == $_ } @seen;
1217 # grab all of the volumes in the list that have
1218 # the same label so they can be merged
1219 my @all = grep { $_->label eq $vol->label } @$vols;
1221 # take note of the fact that we've looked at this set of volumes
1222 push( @seen, $_->id ) for @all;
1224 # for each volume, see if there are any copies that have a
1225 # remote circ_lib (circ_lib != vol->owning_lib and != $o_lib ).
1227 unless( $self->api_name =~ /override/ ) {
1230 $logger->debug("merge: searching for copies with remote circ_lib for volume ".$v->id);
1232 call_number => $v->id,
1233 circ_lib => { "!=" => $v->owning_lib },
1237 my $copies = $e->search_asset_copy($args, {idlist=>1});
1239 # if the copy's circ_lib matches the destination lib,
1241 $copies = [ grep { $_->circ_lib ne $o_lib } @$copies ];
1242 return OpenILS::Event->new('COPY_REMOTE_CIRC_LIB') if @$copies;
1246 # see if there is a volume at the destination lib that
1247 # already has the requested label
1248 my $existing_vol = $e->search_asset_call_number(
1250 label => $vol->label,
1252 owning_lib =>$o_lib,
1257 if( $existing_vol ) {
1259 if( grep { $_->id == $existing_vol->id } @all ) {
1260 # this volume is already accounted for in our list of volumes to merge
1261 $existing_vol = undef;
1264 # this volume exists on the destination record/owning_lib and must
1265 # be used as the destination for merging
1266 $logger->debug("merge: volume already exists at destination record: ".
1267 $existing_vol->id.' : '.$existing_vol->label) if $existing_vol;
1271 if( @all > 1 || $existing_vol ) {
1272 $logger->info("merge: found collisions in volume transfer");
1273 my @args = ($e, \@all);
1274 @args = ($e, \@all, $existing_vol) if $existing_vol;
1275 ($vol, $evt) = OpenILS::Application::Cat::Merge::merge_volumes(@args);
1276 return $evt if $evt;
1279 if( !$existing_vol ) {
1281 $vol->owning_lib($o_lib);
1283 $vol->editor($e->requestor->id);
1284 $vol->edit_date('now');
1286 $logger->info("merge: updating volume ".$vol->id);
1287 $e->update_asset_call_number($vol) or return $e->event;
1290 $logger->info("merge: bypassing volume update because existing volume used as target");
1293 # regardless of what volume was used as the destination,
1294 # update any copies that have moved over to the new lib
1295 my $copies = $e->search_asset_copy({call_number=>$vol->id, deleted => 'f'});
1297 # update circ lib on the copies - make this a method flag?
1298 for my $copy (@$copies) {
1299 next if $copy->circ_lib == $o_lib;
1300 $logger->info("merge: transfer moving circ lib on copy ".$copy->id);
1301 $copy->circ_lib($o_lib);
1302 $copy->editor($e->requestor->id);
1303 $copy->edit_date('now');
1304 $e->update_asset_copy($copy) or return $e->event;
1308 $logger->info("merge: transfer succeeded");