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");
108 $__bib_sources = new_editor()->retrieve_all_config_bib_source()
109 unless $__bib_sources;
111 my ($s) = grep { lc($_->source) eq lc($name) } @$__bib_sources;
119 __PACKAGE__->register_method(
120 method => "create_record_xml",
121 api_name => "open-ils.cat.biblio.record.xml.create.override",
122 signature => q/@see open-ils.cat.biblio.record.xml.create/);
124 __PACKAGE__->register_method(
125 method => "create_record_xml",
126 api_name => "open-ils.cat.biblio.record.xml.create",
128 Inserts a new biblio with the given XML
132 sub create_record_xml {
133 my( $self, $client, $login, $xml, $source ) = @_;
135 my $override = 1 if $self->api_name =~ /override/;
137 my( $user_obj, $evt ) = $U->checksesperm($login, 'CREATE_MARC');
140 $logger->activity("user ".$user_obj->id." creating new MARC record");
142 my $meth = $self->method_lookup("open-ils.cat.biblio.record.xml.import");
144 $meth = $self->method_lookup(
145 "open-ils.cat.biblio.record.xml.import.override") if $override;
147 my ($s) = $meth->run($login, $xml, $source);
153 __PACKAGE__->register_method(
154 method => "biblio_record_replace_marc",
155 api_name => "open-ils.cat.biblio.record.xml.update",
158 Updates the XML for a given biblio record.
159 This does not change any other aspect of the record entry
160 exception the XML, the editor, and the edit date.
161 @return The update record object
165 __PACKAGE__->register_method(
166 method => 'biblio_record_replace_marc',
167 api_name => 'open-ils.cat.biblio.record.marc.replace',
169 @param auth The authtoken
170 @param recid The record whose MARC we're replacing
171 @param newxml The new xml to use
175 __PACKAGE__->register_method(
176 method => 'biblio_record_replace_marc',
177 api_name => 'open-ils.cat.biblio.record.marc.replace.override',
178 signature => q/@see open-ils.cat.biblio.record.marc.replace/
181 sub biblio_record_replace_marc {
182 my( $self, $conn, $auth, $recid, $newxml, $source ) = @_;
184 warn "Updating MARC with xml\n$newxml\n";
186 my $e = OpenILS::Utils::Editor->new(authtoken=>$auth, xact=>1);
188 return $e->event unless $e->checkauth;
189 return $e->event unless $e->allowed('CREATE_MARC');
191 my $rec = $e->retrieve_biblio_record_entry($recid)
194 my $fixtcn = 1 if $self->api_name =~ /replace/o;
196 # See if there is a different record in the database that has our TCN value
197 # If we're not updating the TCN, all we care about it the marcdoc
198 my $override = $self->api_name =~ /override/;
200 my $storage = OpenSRF::AppSession->create('open-ils.storage');
202 my( $tcn, $tsource, $marcdoc, $evt) =
203 _find_tcn_info($e->session, $newxml, $override, $recid);
208 $rec->tcn_value($tcn);
209 $rec->tcn_source($tsource);
212 $rec->source(bib_source_from_name($source)) if $source;
213 $rec->editor($e->requestor->id);
214 $rec->edit_date('now');
215 $rec->marc( entityize( $marcdoc->documentElement->toString ) );
217 $logger->activity("user ".$e->requestor->id." replacing MARC for record $recid");
219 $e->update_biblio_record_entry($rec) or return $e->event;
222 $conn->respond_complete($rec);
226 'open-ils.ingest.full.biblio.record', $recid );
234 __PACKAGE__->register_method(
235 method => "biblio_record_xml_import",
236 api_name => "open-ils.cat.biblio.record.xml.import.override",
237 signature => q/@see open-ils.cat.biblio.record.xml.import/);
239 __PACKAGE__->register_method(
240 method => "biblio_record_xml_import",
241 api_name => "open-ils.cat.biblio.record.xml.import",
242 notes => <<" NOTES");
243 Takes a marcxml record and imports the record into the database. In this
244 case, the marcxml record is assumed to be a complete record (i.e. valid
245 MARC). The title control number is taken from (whichever comes first)
246 tags 001, 039[ab], 020a, 022a, 010, 035a and whichever does not already exist
248 user_session must have IMPORT_MARC permissions
252 sub biblio_record_xml_import {
253 my( $self, $client, $authtoken, $xml, $source) = @_;
255 my $override = 1 if $self->api_name =~ /override/;
257 my( $tcn, $tcn_source, $marcdoc );
258 my( $requestor, $evt ) = $U->checksesperm($authtoken, 'IMPORT_MARC');
261 my $session = $apputils->start_db_session();
263 ( $tcn, $tcn_source, $marcdoc, $evt ) = _find_tcn_info($session, $xml, $override);
266 $logger->activity("user ".$requestor->id.
267 " creating new biblio entry with tcn=$tcn and tcn_source $tcn_source");
269 my $record = Fieldmapper::biblio::record_entry->new;
271 $record->source(bib_source_from_name($source)) if $source;
272 $record->tcn_source($tcn_source);
273 $record->tcn_value($tcn);
274 $record->creator($requestor->id);
275 $record->editor($requestor->id);
276 $record->create_date('now');
277 $record->edit_date('now');
278 $record->marc( entityize( $marcdoc->documentElement->toString ) );
280 my $id = $session->request(
281 "open-ils.storage.direct.biblio.record_entry.create", $record )->gather(1);
283 return $U->DB_UPDATE_FAILED($record) unless $id;
286 $logger->info("marc create/import created new record $id");
288 $apputils->commit_db_session($session);
290 $logger->debug("Sending record off to be wormized");
292 $client->respond_complete($record);
296 'open-ils.ingest.full.biblio.record', $id );
305 my $override = shift;
306 my $existing_rec = shift || 0;
309 my $marcxml = XML::LibXML->new->parse_string( $xml );
310 $marcxml->documentElement->setNamespace(
311 "http://www.loc.gov/MARC21/slim", "marc", 1 );
313 my $xpath = '//marc:controlfield[@tag="001"]';
314 my $tcn = $marcxml->documentElement->findvalue($xpath);
315 $logger->info("biblio import located 001 (tcn) value of $tcn");
317 $xpath = '//marc:controlfield[@tag="003"]';
318 my $tcn_source = $marcxml->documentElement->findvalue($xpath) || "System Local";
320 if(my $rec = _tcn_exists($session, $tcn, $tcn_source, $existing_rec) ) {
323 $tcn = find_free_tcn( $marcxml, $session, $existing_rec );
325 # if we're overriding, try to find a different TCN to use
328 $logger->activity("tcn value $tcn already exists, attempting to override");
336 'OPEN_TCN_NOT_FOUND',
337 payload => $marcxml->toString())
343 $logger->warn("tcn value $origtcn already exists in import/create");
345 # otherwise, return event
351 'TCN_EXISTS', payload => {
361 return ($tcn, $tcn_source, $marcxml);
368 my $existing_rec = shift;
372 my $xpath = '//marc:datafield[@tag="039"]/subfield[@code="a"]';
373 my ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
374 $xpath = '//marc:datafield[@tag="039"]/subfield[@code="b"]';
375 my $tcn_source = $marcxml->documentElement->findvalue($xpath) || "System Local";
377 if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {
385 $xpath = '//marc:datafield[@tag="020"]/subfield[@code="a"]';
386 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
387 $tcn_source = "ISBN";
388 if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
392 $xpath = '//marc:datafield[@tag="022"]/subfield[@code="a"]';
393 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
394 $tcn_source = "ISSN";
395 if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
399 $xpath = '//marc:datafield[@tag="010"]';
400 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
401 $tcn_source = "LCCN";
402 if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
406 $xpath = '//marc:datafield[@tag="035"]/subfield[@code="a"]';
407 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
408 $tcn_source = "System Legacy";
409 if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
412 $marcxml->documentElement->removeChild(
413 $marcxml->documentElement->findnodes( '//datafield[@tag="035"]' )
418 return undef unless $tcn;
421 my $df = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'datafield');
422 $df->setAttribute( tag => '039' );
423 $df->setAttribute( ind1 => ' ' );
424 $df->setAttribute( ind2 => ' ' );
425 $marcxml->documentElement->appendChild( $df );
427 my $sfa = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'subfield');
428 $sfa->setAttribute( code => 'a' );
429 $sfa->appendChild( $marcxml->createTextNode( $tcn ) );
430 $df->appendChild( $sfa );
432 my $sfb = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'subfield');
433 $sfb->setAttribute( code => 'b' );
434 $sfb->appendChild( $marcxml->createTextNode( $tcn_source ) );
435 $df->appendChild( $sfb );
447 my $existing_rec = shift || 0;
449 if(!$tcn) {return 0;}
451 $logger->debug("tcn_exists search for tcn $tcn and source $source and id $existing_rec");
453 # XXX why does the source matter?
454 # my $req = $session->request(
455 # { tcn_value => $tcn, tcn_source => $source, deleted => 'f' } );
457 my $req = $session->request(
458 "open-ils.storage.id_list.biblio.record_entry.search_where.atomic",
459 { tcn_value => $tcn, deleted => 'f', id => {'!=' => $existing_rec} } );
461 my $recs = $req->gather(1);
463 if($recs and $recs->[0]) {
464 $logger->debug("_tcn_exists is true for tcn : $tcn ($source)");
468 $logger->debug("_tcn_exists is false for tcn : $tcn ($source)");
475 # XXX deprecated. Remove me.
479 __PACKAGE__->register_method(
480 method => "biblio_record_tree_retrieve",
481 api_name => "open-ils.cat.biblio.record.tree.retrieve",
484 sub biblio_record_tree_retrieve {
486 my( $self, $client, $recordid ) = @_;
488 my $name = "open-ils.storage.direct.biblio.record_entry.retrieve";
489 my $session = OpenSRF::AppSession->create( "open-ils.storage" );
490 my $request = $session->request( $name, $recordid );
491 my $marcxml = $request->gather(1);
494 throw OpenSRF::EX::ERROR
495 ("No record in database with id $recordid");
498 $session->disconnect();
501 warn "turning into nodeset\n";
502 my $nodes = OpenILS::Utils::FlatXML->new()->xml_to_nodeset( $marcxml->marc );
503 warn "turning nodeset into tree\n";
504 my $tree = $utils->nodeset2tree( $nodes->nodeset );
506 $tree->owner_doc( $marcxml->id() );
508 warn "returning tree\n";
516 __PACKAGE__->register_method(
517 method => "biblio_record_xml_update",
518 api_name => "open-ils.cat.biblio.record.xml.update",
519 argc => 3, #(session_id, biblio_tree )
520 notes => <<' NOTES');
521 Updates the XML of a biblio record entry
522 @param authtoken The session token for the staff updating the record
523 @param docID The record entry ID to update
524 @param xml The new MARCXML record
527 sub biblio_record_xml_update {
529 my( $self, $client, $user_session, $id, $xml ) = @_;
531 my $user_obj = $apputils->check_user_session($user_session);
533 if($apputils->check_user_perms(
534 $user_obj->id, $user_obj->home_ou, "UPDATE_MARC")) {
535 return OpenILS::Perm->new("UPDATE_MARC");
538 $logger->activity("user ".$user_obj->id." updating biblio record $id");
541 my $session = OpenILS::Application::AppUtils->start_db_session();
543 warn "Retrieving biblio record from storage for update\n";
545 my $req1 = $session->request(
546 "open-ils.storage.direct.biblio.record_entry.batch.retrieve", $id );
547 my $biblio = $req1->gather(1);
549 warn "retrieved doc $id\n";
551 my $doc = XML::LibXML->new->parse_string($xml);
552 throw OpenSRF::EX::ERROR ("Invalid XML in record update: $xml") unless $doc;
554 $biblio->marc( entityize( $doc->documentElement->toString ) );
555 $biblio->editor( $user_obj->id );
556 $biblio->edit_date( 'now' );
558 warn "Sending updated doc $id to db with xml ".$biblio->marc. "\n";
560 my $req = $session->request(
561 "open-ils.storage.direct.biblio.record_entry.update", $biblio );
564 my $status = $req->recv();
565 if( !$status || $status->isa("Error") || ! $status->content) {
566 OpenILS::Application::AppUtils->rollback_db_session($session);
567 if($status->isa("Error")) { throw $status ($status); }
568 throw OpenSRF::EX::ERROR ("Error updating biblio record");
572 # Send the doc to the wormer for wormizing
573 warn "Starting worm session\n";
578 my $wreq = $session->request( "open-ils.worm.wormize.biblio", $id );
582 $w = $wreq->gather(1);
586 warn "wormizing failed, rolling back\n";
587 OpenILS::Application::AppUtils->rollback_db_session($session);
589 if($e) { throw $e ($e); }
590 throw OpenSRF::EX::ERROR ("Wormizing Failed for $id" );
593 warn "Committing db session...\n";
594 OpenILS::Application::AppUtils->commit_db_session( $session );
596 # $client->respond_complete($tree);
598 warn "Done wormizing\n";
601 #warn "Returning tree:\n";
612 __PACKAGE__->register_method(
613 method => "biblio_record_record_metadata",
614 api_name => "open-ils.cat.biblio.record.metadata.retrieve",
615 argc => 1, #(session_id, biblio_tree )
616 notes => "Walks the tree and commits any changed nodes " .
617 "adds any new nodes, and deletes any deleted nodes",
620 sub biblio_record_record_metadata {
621 my( $self, $client, $authtoken, $ids ) = @_;
623 return [] unless $ids and @$ids;
625 my $editor = new_editor(authtoken => $authtoken);
626 return $editor->event unless $editor->checkauth;
627 return $editor->event unless $editor->allowed('VIEW_USER');
632 return $editor->event unless
633 my $rec = $editor->retrieve_biblio_record_entry($_);
634 $rec->creator($editor->retrieve_actor_user($rec->creator));
635 $rec->editor($editor->retrieve_actor_user($rec->editor));
636 $rec->clear_marc; # slim the record down
637 push( @results, $rec );
645 __PACKAGE__->register_method(
646 method => "biblio_record_marc_cn",
647 api_name => "open-ils.cat.biblio.record.marc_cn.retrieve",
648 argc => 1, #(bib id )
651 sub biblio_record_marc_cn {
652 my( $self, $client, $id ) = @_;
654 my $session = OpenSRF::AppSession->create("open-ils.cstore");
656 ->request("open-ils.cstore.direct.biblio.record_entry.retrieve", $id )
660 my $doc = XML::LibXML->new->parse_string($marc);
661 $doc->documentElement->setNamespace( "http://www.loc.gov/MARC21/slim", "marc", 1 );
664 for my $tag ( qw/050 055 060 070 080 082 086 088 090 092 096 098 099/ ) {
665 my @node = $doc->findnodes("//marc:datafield[\@tag='$tag']");
667 my $cn = $x->findvalue("marc:subfield[\@code='a' or \@code='b']");
668 push @res, {$tag => $cn} if ($cn);
675 sub _get_id_by_userid {
680 my $session = OpenSRF::AppSession->create( "open-ils.cstore" );
681 my $request = $session->request(
682 "open-ils.cstore.direct.actor.user.search.atomic", { usrname => \@users } );
684 $request->wait_complete;
685 my $response = $request->recv();
686 if(!$request->complete) {
687 throw OpenSRF::EX::ERROR ("no response from cstore on user retrieve");
690 if(UNIVERSAL::isa( $response, "Error")){
691 throw $response ($response);
694 for my $u (@{$response->content}) {
700 $session->disconnect;
707 # commits metadata objects to the db
708 sub _update_record_metadata {
710 my ($session, @docs ) = @_;
712 for my $doc (@docs) {
714 my $user_obj = $doc->{user};
715 my $docid = $doc->{docid};
717 warn "Updating metata for doc $docid\n";
719 my $request = $session->request(
720 "open-ils.storage.direct.biblio.record_entry.retrieve", $docid );
721 my $record = $request->gather(1);
723 warn "retrieved record\n";
724 my ($id) = _get_id_by_userid($user_obj->usrname);
726 warn "got $id from _get_id_by_userid\n";
727 $record->editor($id);
729 warn "Grabbed the record, updating and moving on\n";
731 $request = $session->request(
732 "open-ils.storage.direct.biblio.record_entry.update", $record );
736 warn "committing metarecord update\n";
743 __PACKAGE__->register_method(
744 method => "orgs_for_title",
745 api_name => "open-ils.cat.actor.org_unit.retrieve_by_title"
749 my( $self, $client, $record_id ) = @_;
751 my $vols = $apputils->simple_scalar_request(
753 "open-ils.cstore.direct.asset.call_number.search.atomic",
754 { record => $record_id, deleted => 'f' });
756 my $orgs = { map {$_->owning_lib => 1 } @$vols };
757 return [ keys %$orgs ];
761 __PACKAGE__->register_method(
762 method => "retrieve_copies",
763 api_name => "open-ils.cat.asset.copy_tree.retrieve");
765 __PACKAGE__->register_method(
766 method => "retrieve_copies",
767 api_name => "open-ils.cat.asset.copy_tree.global.retrieve");
769 # user_session may be null/undef
770 sub retrieve_copies {
772 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
774 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
778 warn " $$ retrieving copy tree for orgs @org_ids and doc $docid at " . time() . "\n";
780 # grabbing copy trees should be available for everyone..
781 if(!@org_ids and $user_session) {
783 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
784 @org_ids = ($user_obj->home_ou);
787 if( $self->api_name =~ /global/ ) {
788 warn "performing global copy_tree search for $docid\n";
789 return _build_volume_list( { record => $docid, deleted => 'f' } );
794 for my $orgid (@org_ids) {
795 my $vols = _build_volume_list(
796 { record => $docid, owning_lib => $orgid, deleted => 'f' } );
797 warn "Volumes built for org $orgid\n";
798 push( @all_vols, @$vols );
801 warn " $$ Finished copy_tree at " . time() . "\n";
809 sub _build_volume_list {
810 my $search_hash = shift;
812 $search_hash->{deleted} = 'f';
813 my $e = new_editor();
815 my $vols = $e->search_asset_call_number($search_hash);
819 for my $volume (@$vols) {
821 my $copies = $e->search_asset_copy(
822 { call_number => $volume->id , deleted => 'f' });
824 $copies = [ sort { $a->barcode cmp $b->barcode } @$copies ];
826 for my $c (@$copies) {
827 if( $c->status == OILS_COPY_STATUS_CHECKED_OUT ) {
829 $e->search_action_circulation(
831 { target_copy => $c->id },
833 order_by => { circ => 'xact_start desc' },
842 $volume->copies($copies);
843 push( @volumes, $volume );
846 #$session->disconnect();
852 __PACKAGE__->register_method(
853 method => "fleshed_copy_update",
854 api_name => "open-ils.cat.asset.copy.fleshed.batch.update",);
856 __PACKAGE__->register_method(
857 method => "fleshed_copy_update",
858 api_name => "open-ils.cat.asset.copy.fleshed.batch.update.override",);
861 sub fleshed_copy_update {
862 my( $self, $conn, $auth, $copies, $delete_stats ) = @_;
863 return 1 unless ref $copies;
864 my( $reqr, $evt ) = $U->checkses($auth);
866 my $editor = new_editor(requestor => $reqr, xact => 1);
867 my $override = $self->api_name =~ /override/;
868 $evt = update_fleshed_copies($editor, $override, undef, $copies, $delete_stats);
870 $logger->info("fleshed copy update failed with event: ".JSON->perl2JSON($evt));
875 $logger->info("fleshed copy update successfully updated ".scalar(@$copies)." copies");
880 __PACKAGE__->register_method(
882 api_name => 'open-ils.cat.biblio.records.merge',
884 Merges a group of records
885 @param auth The login session key
886 @param master The id of the record all other r
887 ecords should be merged into
888 @param records Array of records to be merged into the master record
889 @return 1 on success, Event on error.
894 my( $self, $conn, $auth, $master, $records ) = @_;
895 my( $reqr, $evt ) = $U->checkses($auth);
897 my $editor = new_editor( requestor => $reqr, xact => 1 );
898 my $v = OpenILS::Application::Cat::Merge::merge_records($editor, $master, $records);
907 # ---------------------------------------------------------------------------
908 # ---------------------------------------------------------------------------
910 # returns true if the given title (id) has no un-deleted
913 my( $editor, $rid ) = @_;
915 return 0 if $rid == OILS_PRECAT_RECORD;
917 my $cnlist = $editor->search_asset_call_number(
918 { record => $rid, deleted => 'f' }, { idlist => 1 } );
919 return 1 unless @$cnlist;
921 for my $cn (@$cnlist) {
922 my $copylist = $editor->search_asset_copy(
924 { call_number => $cn, deleted => 'f' },
927 return 0 if @$copylist; # false if we find any copies
934 __PACKAGE__->register_method(
935 method => "fleshed_volume_update",
936 api_name => "open-ils.cat.asset.volume.fleshed.batch.update",);
938 __PACKAGE__->register_method(
939 method => "fleshed_volume_update",
940 api_name => "open-ils.cat.asset.volume.fleshed.batch.update.override",);
942 sub fleshed_volume_update {
943 my( $self, $conn, $auth, $volumes, $delete_stats ) = @_;
944 my( $reqr, $evt ) = $U->checkses($auth);
947 my $override = ($self->api_name =~ /override/);
948 my $editor = new_editor( requestor => $reqr, xact => 1 );
950 for my $vol (@$volumes) {
951 $logger->info("vol-update: investigating volume ".$vol->id);
953 $vol->editor($reqr->id);
954 $vol->edit_date('now');
956 my $copies = $vol->copies;
959 $vol->editor($editor->requestor->id);
960 $vol->edit_date('now');
962 if( $vol->isdeleted ) {
964 $logger->info("vol-update: deleting volume");
965 my $cs = $editor->search_asset_copy(
966 { call_number => $vol->id, deleted => 'f' } );
967 return OpenILS::Event->new(
968 'VOLUME_NOT_EMPTY', payload => $vol->id ) if @$cs;
971 return $editor->event unless
972 $editor->update_asset_call_number($vol);
975 } elsif( $vol->isnew ) {
976 $logger->info("vol-update: creating volume");
977 $evt = create_volume( $override, $editor, $vol );
980 } elsif( $vol->ischanged ) {
981 $logger->info("vol-update: update volume");
982 $evt = update_volume($vol, $editor);
986 # now update any attached copies
987 if( @$copies and !$vol->isdeleted ) {
988 $_->call_number($vol->id) for @$copies;
989 $evt = update_fleshed_copies( $editor, $override, $vol, $copies, $delete_stats );
995 return scalar(@$volumes);
1004 return $evt if ( $evt = org_cannot_have_vols($editor, $vol->owning_lib) );
1006 my $vols = $editor->search_asset_call_number( {
1007 owning_lib => $vol->owning_lib,
1008 record => $vol->record,
1009 label => $vol->label,
1014 # There exists a different volume in the DB with the same properties
1015 return OpenILS::Event->new('VOLUME_LABEL_EXISTS', payload => $vol->id)
1016 if grep { $_->id ne $vol->id } @$vols;
1018 return $editor->event unless $editor->update_asset_call_number($vol);
1025 my( $vol, $copy ) = @_;
1026 my $org = $vol->owning_lib;
1027 if( $vol->id == OILS_PRECAT_CALL_NUMBER ) {
1028 $org = ref($copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
1030 $logger->debug("using copy perm org $org");
1035 # this does the actual work
1036 sub update_fleshed_copies {
1037 my( $editor, $override, $vol, $copies, $delete_stats ) = @_;
1040 my $fetchvol = ($vol) ? 0 : 1;
1043 $cache{$vol->id} = $vol if $vol;
1045 for my $copy (@$copies) {
1047 my $copyid = $copy->id;
1048 $logger->info("vol-update: inspecting copy $copyid");
1050 if( !($vol = $cache{$copy->call_number}) ) {
1051 $vol = $cache{$copy->call_number} =
1052 $editor->retrieve_asset_call_number($copy->call_number);
1053 return $editor->event unless $vol;
1056 return $editor->event unless
1057 $editor->allowed('UPDATE_COPY', copy_perm_org($vol, $copy));
1059 $copy->editor($editor->requestor->id);
1060 $copy->edit_date('now');
1062 $copy->status( $copy->status->id ) if ref($copy->status);
1063 $copy->location( $copy->location->id ) if ref($copy->location);
1064 $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
1066 my $sc_entries = $copy->stat_cat_entries;
1067 $copy->clear_stat_cat_entries;
1069 if( $copy->isdeleted ) {
1070 $evt = delete_copy($editor, $override, $vol, $copy);
1071 return $evt if $evt;
1073 } elsif( $copy->isnew ) {
1074 $evt = create_copy( $editor, $vol, $copy );
1075 return $evt if $evt;
1077 } elsif( $copy->ischanged ) {
1079 $evt = update_copy( $editor, $override, $vol, $copy );
1080 return $evt if $evt;
1083 $copy->stat_cat_entries( $sc_entries );
1084 $evt = update_copy_stat_entries($editor, $copy, $delete_stats);
1085 return $evt if $evt;
1088 $logger->debug("vol-update: done updating copy batch");
1093 sub fix_copy_price {
1095 my $p = $copy->price || 0;
1099 my $d = $copy->deposit_amount || 0;
1101 $copy->deposit_amount($d);
1106 my( $editor, $override, $vol, $copy ) = @_;
1109 my $org = (ref $copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
1110 return $evt if ( $evt = org_cannot_have_vols($editor, $org) );
1112 $logger->info("vol-update: updating copy ".$copy->id);
1113 my $orig_copy = $editor->retrieve_asset_copy($copy->id);
1114 my $orig_vol = $editor->retrieve_asset_call_number($copy->call_number);
1116 $copy->editor($editor->requestor->id);
1117 $copy->edit_date('now');
1119 $copy->age_protect( $copy->age_protect->id )
1120 if ref $copy->age_protect;
1122 fix_copy_price($copy);
1124 return $editor->event unless $editor->update_asset_copy($copy);
1125 return remove_empty_objects($editor, $override, $orig_vol);
1129 sub remove_empty_objects {
1130 my( $editor, $override, $vol ) = @_;
1131 if( title_is_empty($editor, $vol->record) ) {
1133 # disable the TITLE_LAST_COPY event for now
1137 # delete this volume if it's not already marked as deleted
1138 unless( $U->is_true($vol->deleted) || $vol->isdeleted ) {
1140 $vol->editor($editor->requestor->id);
1141 $vol->edit_date('now');
1142 $editor->update_asset_call_number($vol) or return $editor->event;
1145 # then delete the record this volume points to
1146 my $rec = $editor->retrieve_biblio_record_entry($vol->record)
1147 or return $editor->event;
1149 unless( $U->is_true($rec->deleted) ) {
1152 $editor->update_biblio_record_entry($rec) or return $editor->event;
1156 return OpenILS::Event->new('TITLE_LAST_COPY', payload => $vol->record );
1165 my( $editor, $override, $vol, $copy ) = @_;
1167 my $stat = $U->copy_status($copy->status)->id;
1170 return OpenILS::Event->new('COPY_DELETE_WARNING', payload => $copy->id )
1171 if $stat == OILS_COPY_STATUS_CHECKED_OUT or
1172 $stat == OILS_COPY_STATUS_IN_TRANSIT or
1173 $stat == OILS_COPY_STATUS_ON_HOLDS_SHELF or
1174 $stat == OILS_COPY_STATUS_ILL;
1177 $logger->info("vol-update: deleting copy ".$copy->id);
1178 $copy->deleted('t');
1180 $copy->editor($editor->requestor->id);
1181 $copy->edit_date('now');
1182 $editor->update_asset_copy($copy) or return $editor->event;
1184 # Delete any open transits for this copy
1185 my $transits = $editor->search_action_transit_copy(
1186 { target_copy=>$copy->id, dest_recv_time => undef } );
1188 for my $t (@$transits) {
1189 $editor->delete_action_transit_copy($t)
1190 or return $editor->event;
1193 return remove_empty_objects($editor, $override, $vol);
1198 my( $editor, $vol, $copy ) = @_;
1200 my $existing = $editor->search_asset_copy(
1201 { barcode => $copy->barcode, deleted => 'f' } );
1203 return OpenILS::Event->new('ITEM_BARCODE_EXISTS') if @$existing;
1206 my $org = (ref $copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
1207 return $evt if ( $evt = org_cannot_have_vols($editor, $org) );
1210 $copy->creator($editor->requestor->id);
1211 $copy->create_date('now');
1212 fix_copy_price($copy);
1214 $editor->create_asset_copy($copy) or return $editor->event;
1218 # if 'delete_stats' is true, the copy->stat_cat_entries data is
1219 # treated as the authoritative list for the copy. existing entries
1220 # that are not in said list will be deleted from the DB
1221 sub update_copy_stat_entries {
1222 my( $editor, $copy, $delete_stats ) = @_;
1224 return undef if $copy->isdeleted;
1225 return undef unless $copy->ischanged or $copy->isnew;
1228 my $entries = $copy->stat_cat_entries;
1230 if( $delete_stats ) {
1231 $entries = ($entries and @$entries) ? $entries : [];
1233 return undef unless ($entries and @$entries);
1236 my $maps = $editor->search_asset_stat_cat_entry_copy_map({owning_copy=>$copy->id});
1239 # if there is no stat cat entry on the copy who's id matches the
1240 # current map's id, remove the map from the database
1241 for my $map (@$maps) {
1242 if(! grep { $_->id == $map->stat_cat_entry } @$entries ) {
1244 $logger->info("copy update found stale ".
1245 "stat cat entry map ".$map->id. " on copy ".$copy->id);
1247 $editor->delete_asset_stat_cat_entry_copy_map($map)
1248 or return $editor->event;
1253 # go through the stat cat update/create process
1254 for my $entry (@$entries) {
1257 # if this link already exists in the DB, don't attempt to re-create it
1258 next if( grep{$_->stat_cat_entry == $entry->id} @$maps );
1260 my $new_map = Fieldmapper::asset::stat_cat_entry_copy_map->new();
1262 my $sc = ref($entry->stat_cat) ? $entry->stat_cat->id : $entry->stat_cat;
1264 $new_map->stat_cat( $sc );
1265 $new_map->stat_cat_entry( $entry->id );
1266 $new_map->owning_copy( $copy->id );
1268 $editor->create_asset_stat_cat_entry_copy_map($new_map)
1269 or return $editor->event;
1271 $logger->info("copy update created new stat cat entry map ".$editor->data);
1279 my( $override, $editor, $vol ) = @_;
1282 return $evt if ( $evt = org_cannot_have_vols($editor, $vol->owning_lib) );
1284 # first lets see if there are any collisions
1285 my $vols = $editor->search_asset_call_number( {
1286 owning_lib => $vol->owning_lib,
1287 record => $vol->record,
1288 label => $vol->label,
1296 $label = $vol->label;
1298 return OpenILS::Event->new(
1299 'VOLUME_LABEL_EXISTS', payload => $vol->id);
1303 # create a temp label so we can create the volume, then de-dup it
1304 $vol->label( '__SYSTEM_TMP_'.time) if $label;
1306 $vol->creator($editor->requestor->id);
1307 $vol->create_date('now');
1308 $vol->editor($editor->requestor->id);
1309 $vol->edit_date('now');
1312 $editor->create_asset_call_number($vol) or return $editor->event;
1315 # now restore the label and merge into the existing record
1316 $vol->label($label);
1318 OpenILS::Application::Cat::Merge::merge_volumes($editor, [$vol], $$vols[0]);
1319 return $evt if $evt;
1326 __PACKAGE__->register_method (
1327 method => 'batch_volume_transfer',
1328 api_name => 'open-ils.cat.asset.volume.batch.transfer',
1331 __PACKAGE__->register_method (
1332 method => 'batch_volume_transfer',
1333 api_name => 'open-ils.cat.asset.volume.batch.transfer.override',
1337 sub batch_volume_transfer {
1338 my( $self, $conn, $auth, $args ) = @_;
1341 my $rec = $$args{docid};
1342 my $o_lib = $$args{lib};
1343 my $vol_ids = $$args{volumes};
1345 my $override = 1 if $self->api_name =~ /override/;
1347 $logger->info("merge: transferring volumes to lib=$o_lib and record=$rec");
1349 my $e = new_editor(authtoken => $auth, xact =>1);
1350 return $e->event unless $e->checkauth;
1351 return $e->event unless $e->allowed('VOLUME_UPDATE', $o_lib);
1353 my $dorg = $e->retrieve_actor_org_unit($o_lib)
1354 or return $e->event;
1356 my $ou_type = $e->retrieve_actor_org_unit_type($dorg->ou_type)
1357 or return $e->event;
1359 return $evt if ( $evt = org_cannot_have_vols($e, $o_lib) );
1361 my $vols = $e->batch_retrieve_asset_call_number($vol_ids);
1364 for my $vol (@$vols) {
1366 # if we've already looked at this volume, go to the next
1367 next if !$vol or grep { $vol->id == $_ } @seen;
1369 # grab all of the volumes in the list that have
1370 # the same label so they can be merged
1371 my @all = grep { $_->label eq $vol->label } @$vols;
1373 # take note of the fact that we've looked at this set of volumes
1374 push( @seen, $_->id ) for @all;
1376 # for each volume, see if there are any copies that have a
1377 # remote circ_lib (circ_lib != vol->owning_lib and != $o_lib ).
1379 unless( $override ) {
1382 $logger->debug("merge: searching for copies with remote circ_lib for volume ".$v->id);
1384 call_number => $v->id,
1385 circ_lib => { "not in" => [ $o_lib, $v->owning_lib ] },
1389 my $copies = $e->search_asset_copy($args, {idlist=>1});
1391 # if the copy's circ_lib matches the destination lib,
1393 return OpenILS::Event->new('COPY_REMOTE_CIRC_LIB') if @$copies;
1397 # see if there is a volume at the destination lib that
1398 # already has the requested label
1399 my $existing_vol = $e->search_asset_call_number(
1401 label => $vol->label,
1403 owning_lib =>$o_lib,
1408 if( $existing_vol ) {
1410 if( grep { $_->id == $existing_vol->id } @all ) {
1411 # this volume is already accounted for in our list of volumes to merge
1412 $existing_vol = undef;
1415 # this volume exists on the destination record/owning_lib and must
1416 # be used as the destination for merging
1417 $logger->debug("merge: volume already exists at destination record: ".
1418 $existing_vol->id.' : '.$existing_vol->label) if $existing_vol;
1422 if( @all > 1 || $existing_vol ) {
1423 $logger->info("merge: found collisions in volume transfer");
1424 my @args = ($e, \@all);
1425 @args = ($e, \@all, $existing_vol) if $existing_vol;
1426 ($vol, $evt) = OpenILS::Application::Cat::Merge::merge_volumes(@args);
1427 return $evt if $evt;
1430 if( !$existing_vol ) {
1432 $vol->owning_lib($o_lib);
1434 $vol->editor($e->requestor->id);
1435 $vol->edit_date('now');
1437 $logger->info("merge: updating volume ".$vol->id);
1438 $e->update_asset_call_number($vol) or return $e->event;
1441 $logger->info("merge: bypassing volume update because existing volume used as target");
1444 # regardless of what volume was used as the destination,
1445 # update any copies that have moved over to the new lib
1446 my $copies = $e->search_asset_copy({call_number=>$vol->id, deleted => 'f'});
1448 # update circ lib on the copies - make this a method flag?
1449 for my $copy (@$copies) {
1450 next if $copy->circ_lib == $o_lib;
1451 $logger->info("merge: transfer moving circ lib on copy ".$copy->id);
1452 $copy->circ_lib($o_lib);
1453 $copy->editor($e->requestor->id);
1454 $copy->edit_date('now');
1455 $e->update_asset_copy($copy) or return $e->event;
1458 # Now see if any empty records need to be deleted after all of this
1460 $evt = remove_empty_objects($e, $override, $_);
1461 return $evt if $evt;
1465 $logger->info("merge: transfer succeeded");
1472 sub org_cannot_have_vols {
1476 my $org = $e->retrieve_actor_org_unit($org_id)
1477 or return $e->event;
1479 my $ou_type = $e->retrieve_actor_org_unit_type($org->ou_type)
1480 or return $e->event;
1482 return OpenILS::Event->new('ORG_CANNOT_HAVE_VOLS')
1483 unless $U->is_true($ou_type->can_have_vols);
1491 __PACKAGE__->register_method(
1492 api_name => 'open-ils.cat.call_number.find_or_create',
1493 method => 'find_or_create_volume',
1496 sub find_or_create_volume {
1497 my( $self, $conn, $auth, $label, $record_id, $org_id ) = @_;
1498 my $e = new_editor(authtoken=>$auth, xact=>1);
1499 return $e->die_event unless $e->checkauth;
1501 my $vol = $e->search_asset_call_number(
1502 {label => $label, record => $record_id, owning_lib => $org_id, deleted => 'f'},
1506 # If the volume exists, return the ID
1507 if( $vol ) { $e->rollback; return $vol; }
1509 # -----------------------------------------------------------------
1510 # Otherwise, create a new volume with the given attributes
1511 # -----------------------------------------------------------------
1513 return $e->die_event unless $e->allowed('VOLUME_UPDATE', $org_id);
1515 $vol = Fieldmapper::asset::call_number->new;
1516 $vol->owning_lib($org_id);
1517 $vol->label($label);
1518 $vol->record($record_id);
1519 $vol->creator($e->requestor->id);
1520 $vol->create_date('now');
1521 $vol->editor($e->requestor->id);
1522 $vol->edit_date('now');
1524 $e->create_asset_call_number($vol) or return $e->die_event;