1 use strict; use warnings;
2 package OpenILS::Application::Cat;
3 use OpenILS::Application::AppUtils;
4 use OpenSRF::Application;
5 use OpenILS::Application::Cat::Utils;
6 use OpenILS::Application::Cat::Merge;
7 use base qw/OpenSRF::Application/;
8 use Time::HiRes qw(time);
9 use OpenSRF::EX qw(:try);
11 use OpenILS::Utils::Fieldmapper;
13 use OpenILS::Const qw/:const/;
16 use Unicode::Normalize;
18 use OpenILS::Utils::FlatXML;
19 use OpenILS::Utils::CStoreEditor q/:funcs/;
20 use OpenILS::Utils::Editor;
22 use OpenSRF::Utils::SettingsClient;
23 use OpenSRF::Utils::Logger qw($logger);
24 use OpenSRF::AppSession;
26 my $apputils = "OpenILS::Application::AppUtils";
28 my $utils = "OpenILS::Application::Cat::Utils";
29 my $U = "OpenILS::Application::AppUtils";
37 my $form = shift || "";
45 $stuff =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
49 __PACKAGE__->register_method(
50 method => "retrieve_marc_template",
51 api_name => "open-ils.cat.biblio.marc_template.retrieve",
53 Returns a MARC 'record tree' based on a set of pre-defined templates.
54 Templates include : book
57 sub retrieve_marc_template {
58 my( $self, $client, $type ) = @_;
59 return $marctemplates{$type} if defined($marctemplates{$type});
60 $marctemplates{$type} = _load_marc_template($type);
61 return $marctemplates{$type};
64 __PACKAGE__->register_method(
65 method => 'fetch_marc_template_types',
66 api_name => 'open-ils.cat.marc_template.types.retrieve'
69 my $marc_template_files;
71 sub fetch_marc_template_types {
72 my( $self, $conn ) = @_;
73 __load_marc_templates();
74 return [ keys %$marc_template_files ];
77 sub __load_marc_templates {
78 return if $marc_template_files;
79 if(!$conf) { $conf = OpenSRF::Utils::SettingsClient->new; }
81 $marc_template_files = $conf->config_value(
82 "apps", "open-ils.cat","app_settings", "marctemplates" );
84 $logger->info("Loaded marc templates: " . Dumper($marc_template_files));
87 sub _load_marc_template {
90 __load_marc_templates();
92 my $template = $$marc_template_files{$type};
93 open( F, $template ) or
94 throw OpenSRF::EX::ERROR ("Unable to open MARC template file: $template : $@");
98 my $xml = join('', @xml);
100 return XML::LibXML->new->parse_string($xml)->documentElement->toString;
104 sub bib_source_from_name {
106 $logger->debug("searching for bib source: $name");
110 my ($s) = grep { lc($_->source) eq lc($name) } @$__bib_sources;
117 __PACKAGE__->register_method(
118 method => 'fetch_bib_sources',
119 api_name => 'open-ils.cat.bib_sources.retrieve.all');
121 sub fetch_bib_sources {
122 $__bib_sources = new_editor()->retrieve_all_config_bib_source()
123 unless $__bib_sources;
124 return $__bib_sources;
129 __PACKAGE__->register_method(
130 method => "create_record_xml",
131 api_name => "open-ils.cat.biblio.record.xml.create.override",
132 signature => q/@see open-ils.cat.biblio.record.xml.create/);
134 __PACKAGE__->register_method(
135 method => "create_record_xml",
136 api_name => "open-ils.cat.biblio.record.xml.create",
138 Inserts a new biblio with the given XML
142 sub create_record_xml {
143 my( $self, $client, $login, $xml, $source ) = @_;
145 my $override = 1 if $self->api_name =~ /override/;
147 my( $user_obj, $evt ) = $U->checksesperm($login, 'CREATE_MARC');
150 $logger->activity("user ".$user_obj->id." creating new MARC record");
152 my $meth = $self->method_lookup("open-ils.cat.biblio.record.xml.import");
154 $meth = $self->method_lookup(
155 "open-ils.cat.biblio.record.xml.import.override") if $override;
157 my ($s) = $meth->run($login, $xml, $source);
163 __PACKAGE__->register_method(
164 method => "biblio_record_replace_marc",
165 api_name => "open-ils.cat.biblio.record.xml.update",
168 Updates the XML for a given biblio record.
169 This does not change any other aspect of the record entry
170 exception the XML, the editor, and the edit date.
171 @return The update record object
175 __PACKAGE__->register_method(
176 method => 'biblio_record_replace_marc',
177 api_name => 'open-ils.cat.biblio.record.marc.replace',
179 @param auth The authtoken
180 @param recid The record whose MARC we're replacing
181 @param newxml The new xml to use
185 __PACKAGE__->register_method(
186 method => 'biblio_record_replace_marc',
187 api_name => 'open-ils.cat.biblio.record.marc.replace.override',
188 signature => q/@see open-ils.cat.biblio.record.marc.replace/
191 sub biblio_record_replace_marc {
192 my( $self, $conn, $auth, $recid, $newxml, $source ) = @_;
194 warn "Updating MARC with xml\n$newxml\n";
196 my $e = OpenILS::Utils::Editor->new(authtoken=>$auth, xact=>1);
198 return $e->event unless $e->checkauth;
199 return $e->event unless $e->allowed('CREATE_MARC');
201 my $rec = $e->retrieve_biblio_record_entry($recid)
204 my $fixtcn = 1 if $self->api_name =~ /replace/o;
206 # See if there is a different record in the database that has our TCN value
207 # If we're not updating the TCN, all we care about it the marcdoc
208 my $override = $self->api_name =~ /override/;
210 my $storage = OpenSRF::AppSession->create('open-ils.storage');
212 my( $tcn, $tsource, $marcdoc, $evt) =
213 _find_tcn_info($e->session, $newxml, $override, $recid);
218 $rec->tcn_value($tcn);
219 $rec->tcn_source($tsource);
222 $rec->source(bib_source_from_name($source)) if $source;
223 $rec->editor($e->requestor->id);
224 $rec->edit_date('now');
225 $rec->marc( entityize( $marcdoc->documentElement->toString ) );
227 $logger->activity("user ".$e->requestor->id." replacing MARC for record $recid");
229 $e->update_biblio_record_entry($rec) or return $e->event;
232 $conn->respond_complete($rec);
236 'open-ils.ingest.full.biblio.record', $recid );
244 __PACKAGE__->register_method(
245 method => "biblio_record_xml_import",
246 api_name => "open-ils.cat.biblio.record.xml.import.override",
247 signature => q/@see open-ils.cat.biblio.record.xml.import/);
249 __PACKAGE__->register_method(
250 method => "biblio_record_xml_import",
251 api_name => "open-ils.cat.biblio.record.xml.import",
252 notes => <<" NOTES");
253 Takes a marcxml record and imports the record into the database. In this
254 case, the marcxml record is assumed to be a complete record (i.e. valid
255 MARC). The title control number is taken from (whichever comes first)
256 tags 001, 039[ab], 020a, 022a, 010, 035a and whichever does not already exist
258 user_session must have IMPORT_MARC permissions
262 sub biblio_record_xml_import {
263 my( $self, $client, $authtoken, $xml, $source, $auto_tcn) = @_;
265 my $override = 1 if $self->api_name =~ /override/;
267 my( $tcn, $tcn_source, $marcdoc );
268 my( $requestor, $evt ) = $U->checksesperm($authtoken, 'IMPORT_MARC');
271 my $session = $apputils->start_db_session();
274 # auto_tcn forces a blank TCN value so the DB will have to generate one for us
275 $marcdoc = __make_marc_doc($xml);
277 ( $tcn, $tcn_source, $marcdoc, $evt ) = _find_tcn_info($session, $xml, $override);
281 $logger->activity("user ".$requestor->id.
282 " creating new biblio entry with tcn=$tcn and tcn_source $tcn_source");
284 my $record = Fieldmapper::biblio::record_entry->new;
286 $record->source(bib_source_from_name($source)) if $source;
287 $record->tcn_source($tcn_source);
288 $record->tcn_value($tcn);
289 $record->creator($requestor->id);
290 $record->editor($requestor->id);
291 $record->create_date('now');
292 $record->edit_date('now');
293 $record->marc( entityize( $marcdoc->documentElement->toString ) );
295 my $id = $session->request(
296 "open-ils.storage.direct.biblio.record_entry.create", $record )->gather(1);
298 return $U->DB_UPDATE_FAILED($record) unless $id;
301 $logger->info("marc create/import created new record $id");
303 $apputils->commit_db_session($session);
305 $logger->debug("Sending record off to be wormized");
307 $client->respond_complete($record);
311 'open-ils.ingest.full.biblio.record', $id );
316 sub __make_marc_doc {
318 my $marcxml = XML::LibXML->new->parse_string( $xml );
319 $marcxml->documentElement->setNamespace(
320 "http://www.loc.gov/MARC21/slim", "marc", 1 );
328 my $override = shift;
329 my $existing_rec = shift || 0;
332 my $marcxml = __make_marc_doc($xml);
333 # my $marcxml = XML::LibXML->new->parse_string( $xml );
334 # $marcxml->documentElement->setNamespace(
335 # "http://www.loc.gov/MARC21/slim", "marc", 1 );
337 my $xpath = '//marc:controlfield[@tag="001"]';
338 my $tcn = $marcxml->documentElement->findvalue($xpath);
339 $logger->info("biblio import located 001 (tcn) value of $tcn");
341 $xpath = '//marc:controlfield[@tag="003"]';
342 my $tcn_source = $marcxml->documentElement->findvalue($xpath) || "System Local";
344 if(my $rec = _tcn_exists($session, $tcn, $tcn_source, $existing_rec) ) {
347 $tcn = find_free_tcn( $marcxml, $session, $existing_rec );
349 # if we're overriding, try to find a different TCN to use
352 $logger->activity("tcn value $tcn already exists, attempting to override");
360 'OPEN_TCN_NOT_FOUND',
361 payload => $marcxml->toString())
367 $logger->warn("tcn value $origtcn already exists in import/create");
369 # otherwise, return event
375 'TCN_EXISTS', payload => {
385 return ($tcn, $tcn_source, $marcxml);
392 my $existing_rec = shift;
396 my $xpath = '//marc:datafield[@tag="039"]/subfield[@code="a"]';
397 my ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
398 $xpath = '//marc:datafield[@tag="039"]/subfield[@code="b"]';
399 my $tcn_source = $marcxml->documentElement->findvalue($xpath) || "System Local";
401 if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {
409 $xpath = '//marc:datafield[@tag="020"]/subfield[@code="a"]';
410 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
411 $tcn_source = "ISBN";
412 if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
416 $xpath = '//marc:datafield[@tag="022"]/subfield[@code="a"]';
417 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
418 $tcn_source = "ISSN";
419 if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
423 $xpath = '//marc:datafield[@tag="010"]';
424 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
425 $tcn_source = "LCCN";
426 if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
430 $xpath = '//marc:datafield[@tag="035"]/subfield[@code="a"]';
431 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
432 $tcn_source = "System Legacy";
433 if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
436 $marcxml->documentElement->removeChild(
437 $marcxml->documentElement->findnodes( '//datafield[@tag="035"]' )
442 return undef unless $tcn;
445 my $df = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'datafield');
446 $df->setAttribute( tag => '039' );
447 $df->setAttribute( ind1 => ' ' );
448 $df->setAttribute( ind2 => ' ' );
449 $marcxml->documentElement->appendChild( $df );
451 my $sfa = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'subfield');
452 $sfa->setAttribute( code => 'a' );
453 $sfa->appendChild( $marcxml->createTextNode( $tcn ) );
454 $df->appendChild( $sfa );
456 my $sfb = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'subfield');
457 $sfb->setAttribute( code => 'b' );
458 $sfb->appendChild( $marcxml->createTextNode( $tcn_source ) );
459 $df->appendChild( $sfb );
471 my $existing_rec = shift || 0;
473 if(!$tcn) {return 0;}
475 $logger->debug("tcn_exists search for tcn $tcn and source $source and id $existing_rec");
477 # XXX why does the source matter?
478 # my $req = $session->request(
479 # { tcn_value => $tcn, tcn_source => $source, deleted => 'f' } );
481 my $req = $session->request(
482 "open-ils.storage.id_list.biblio.record_entry.search_where.atomic",
483 { tcn_value => $tcn, deleted => 'f', id => {'!=' => $existing_rec} } );
485 my $recs = $req->gather(1);
487 if($recs and $recs->[0]) {
488 $logger->debug("_tcn_exists is true for tcn : $tcn ($source)");
492 $logger->debug("_tcn_exists is false for tcn : $tcn ($source)");
499 # XXX deprecated. Remove me.
503 __PACKAGE__->register_method(
504 method => "biblio_record_tree_retrieve",
505 api_name => "open-ils.cat.biblio.record.tree.retrieve",
508 sub biblio_record_tree_retrieve {
510 my( $self, $client, $recordid ) = @_;
512 my $name = "open-ils.storage.direct.biblio.record_entry.retrieve";
513 my $session = OpenSRF::AppSession->create( "open-ils.storage" );
514 my $request = $session->request( $name, $recordid );
515 my $marcxml = $request->gather(1);
518 throw OpenSRF::EX::ERROR
519 ("No record in database with id $recordid");
522 $session->disconnect();
525 warn "turning into nodeset\n";
526 my $nodes = OpenILS::Utils::FlatXML->new()->xml_to_nodeset( $marcxml->marc );
527 warn "turning nodeset into tree\n";
528 my $tree = $utils->nodeset2tree( $nodes->nodeset );
530 $tree->owner_doc( $marcxml->id() );
532 warn "returning tree\n";
540 __PACKAGE__->register_method(
541 method => "biblio_record_xml_update",
542 api_name => "open-ils.cat.biblio.record.xml.update",
543 argc => 3, #(session_id, biblio_tree )
544 notes => <<' NOTES');
545 Updates the XML of a biblio record entry
546 @param authtoken The session token for the staff updating the record
547 @param docID The record entry ID to update
548 @param xml The new MARCXML record
551 sub biblio_record_xml_update {
553 my( $self, $client, $user_session, $id, $xml ) = @_;
555 my $user_obj = $apputils->check_user_session($user_session);
557 if($apputils->check_user_perms(
558 $user_obj->id, $user_obj->home_ou, "UPDATE_MARC")) {
559 return OpenILS::Perm->new("UPDATE_MARC");
562 $logger->activity("user ".$user_obj->id." updating biblio record $id");
565 my $session = OpenILS::Application::AppUtils->start_db_session();
567 warn "Retrieving biblio record from storage for update\n";
569 my $req1 = $session->request(
570 "open-ils.storage.direct.biblio.record_entry.batch.retrieve", $id );
571 my $biblio = $req1->gather(1);
573 warn "retrieved doc $id\n";
575 my $doc = XML::LibXML->new->parse_string($xml);
576 throw OpenSRF::EX::ERROR ("Invalid XML in record update: $xml") unless $doc;
578 $biblio->marc( entityize( $doc->documentElement->toString ) );
579 $biblio->editor( $user_obj->id );
580 $biblio->edit_date( 'now' );
582 warn "Sending updated doc $id to db with xml ".$biblio->marc. "\n";
584 my $req = $session->request(
585 "open-ils.storage.direct.biblio.record_entry.update", $biblio );
588 my $status = $req->recv();
589 if( !$status || $status->isa("Error") || ! $status->content) {
590 OpenILS::Application::AppUtils->rollback_db_session($session);
591 if($status->isa("Error")) { throw $status ($status); }
592 throw OpenSRF::EX::ERROR ("Error updating biblio record");
596 # Send the doc to the wormer for wormizing
597 warn "Starting worm session\n";
602 my $wreq = $session->request( "open-ils.worm.wormize.biblio", $id );
606 $w = $wreq->gather(1);
610 warn "wormizing failed, rolling back\n";
611 OpenILS::Application::AppUtils->rollback_db_session($session);
613 if($e) { throw $e ($e); }
614 throw OpenSRF::EX::ERROR ("Wormizing Failed for $id" );
617 warn "Committing db session...\n";
618 OpenILS::Application::AppUtils->commit_db_session( $session );
620 # $client->respond_complete($tree);
622 warn "Done wormizing\n";
625 #warn "Returning tree:\n";
636 __PACKAGE__->register_method(
637 method => "biblio_record_record_metadata",
638 api_name => "open-ils.cat.biblio.record.metadata.retrieve",
639 argc => 1, #(session_id, biblio_tree )
640 notes => "Walks the tree and commits any changed nodes " .
641 "adds any new nodes, and deletes any deleted nodes",
644 sub biblio_record_record_metadata {
645 my( $self, $client, $authtoken, $ids ) = @_;
647 return [] unless $ids and @$ids;
649 my $editor = new_editor(authtoken => $authtoken);
650 return $editor->event unless $editor->checkauth;
651 return $editor->event unless $editor->allowed('VIEW_USER');
656 return $editor->event unless
657 my $rec = $editor->retrieve_biblio_record_entry($_);
658 $rec->creator($editor->retrieve_actor_user($rec->creator));
659 $rec->editor($editor->retrieve_actor_user($rec->editor));
660 $rec->clear_marc; # slim the record down
661 push( @results, $rec );
669 __PACKAGE__->register_method(
670 method => "biblio_record_marc_cn",
671 api_name => "open-ils.cat.biblio.record.marc_cn.retrieve",
672 argc => 1, #(bib id )
675 sub biblio_record_marc_cn {
676 my( $self, $client, $id ) = @_;
678 my $session = OpenSRF::AppSession->create("open-ils.cstore");
680 ->request("open-ils.cstore.direct.biblio.record_entry.retrieve", $id )
684 my $doc = XML::LibXML->new->parse_string($marc);
685 $doc->documentElement->setNamespace( "http://www.loc.gov/MARC21/slim", "marc", 1 );
688 for my $tag ( qw/050 055 060 070 080 082 086 088 090 092 096 098 099/ ) {
689 my @node = $doc->findnodes("//marc:datafield[\@tag='$tag']");
691 my $cn = $x->findvalue("marc:subfield[\@code='a' or \@code='b']");
692 push @res, {$tag => $cn} if ($cn);
699 sub _get_id_by_userid {
704 my $session = OpenSRF::AppSession->create( "open-ils.cstore" );
705 my $request = $session->request(
706 "open-ils.cstore.direct.actor.user.search.atomic", { usrname => \@users } );
708 $request->wait_complete;
709 my $response = $request->recv();
710 if(!$request->complete) {
711 throw OpenSRF::EX::ERROR ("no response from cstore on user retrieve");
714 if(UNIVERSAL::isa( $response, "Error")){
715 throw $response ($response);
718 for my $u (@{$response->content}) {
724 $session->disconnect;
731 # commits metadata objects to the db
732 sub _update_record_metadata {
734 my ($session, @docs ) = @_;
736 for my $doc (@docs) {
738 my $user_obj = $doc->{user};
739 my $docid = $doc->{docid};
741 warn "Updating metata for doc $docid\n";
743 my $request = $session->request(
744 "open-ils.storage.direct.biblio.record_entry.retrieve", $docid );
745 my $record = $request->gather(1);
747 warn "retrieved record\n";
748 my ($id) = _get_id_by_userid($user_obj->usrname);
750 warn "got $id from _get_id_by_userid\n";
751 $record->editor($id);
753 warn "Grabbed the record, updating and moving on\n";
755 $request = $session->request(
756 "open-ils.storage.direct.biblio.record_entry.update", $record );
760 warn "committing metarecord update\n";
767 __PACKAGE__->register_method(
768 method => "orgs_for_title",
769 api_name => "open-ils.cat.actor.org_unit.retrieve_by_title"
773 my( $self, $client, $record_id ) = @_;
775 my $vols = $apputils->simple_scalar_request(
777 "open-ils.cstore.direct.asset.call_number.search.atomic",
778 { record => $record_id, deleted => 'f' });
780 my $orgs = { map {$_->owning_lib => 1 } @$vols };
781 return [ keys %$orgs ];
785 __PACKAGE__->register_method(
786 method => "retrieve_copies",
787 api_name => "open-ils.cat.asset.copy_tree.retrieve");
789 __PACKAGE__->register_method(
790 method => "retrieve_copies",
791 api_name => "open-ils.cat.asset.copy_tree.global.retrieve");
793 # user_session may be null/undef
794 sub retrieve_copies {
796 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
798 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
802 warn " $$ retrieving copy tree for orgs @org_ids and doc $docid at " . time() . "\n";
804 # grabbing copy trees should be available for everyone..
805 if(!@org_ids and $user_session) {
807 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
808 @org_ids = ($user_obj->home_ou);
811 if( $self->api_name =~ /global/ ) {
812 warn "performing global copy_tree search for $docid\n";
813 return _build_volume_list( { record => $docid, deleted => 'f' } );
818 for my $orgid (@org_ids) {
819 my $vols = _build_volume_list(
820 { record => $docid, owning_lib => $orgid, deleted => 'f' } );
821 warn "Volumes built for org $orgid\n";
822 push( @all_vols, @$vols );
825 warn " $$ Finished copy_tree at " . time() . "\n";
833 sub _build_volume_list {
834 my $search_hash = shift;
836 $search_hash->{deleted} = 'f';
837 my $e = new_editor();
839 my $vols = $e->search_asset_call_number($search_hash);
843 for my $volume (@$vols) {
845 my $copies = $e->search_asset_copy(
846 { call_number => $volume->id , deleted => 'f' });
848 $copies = [ sort { $a->barcode cmp $b->barcode } @$copies ];
850 for my $c (@$copies) {
851 if( $c->status == OILS_COPY_STATUS_CHECKED_OUT ) {
853 $e->search_action_circulation(
855 { target_copy => $c->id },
857 order_by => { circ => 'xact_start desc' },
866 $volume->copies($copies);
867 push( @volumes, $volume );
870 #$session->disconnect();
876 __PACKAGE__->register_method(
877 method => "fleshed_copy_update",
878 api_name => "open-ils.cat.asset.copy.fleshed.batch.update",);
880 __PACKAGE__->register_method(
881 method => "fleshed_copy_update",
882 api_name => "open-ils.cat.asset.copy.fleshed.batch.update.override",);
885 sub fleshed_copy_update {
886 my( $self, $conn, $auth, $copies, $delete_stats ) = @_;
887 return 1 unless ref $copies;
888 my( $reqr, $evt ) = $U->checkses($auth);
890 my $editor = new_editor(requestor => $reqr, xact => 1);
891 my $override = $self->api_name =~ /override/;
892 $evt = update_fleshed_copies($editor, $override, undef, $copies, $delete_stats);
894 $logger->info("fleshed copy update failed with event: ".JSON->perl2JSON($evt));
899 $logger->info("fleshed copy update successfully updated ".scalar(@$copies)." copies");
904 __PACKAGE__->register_method(
906 api_name => 'open-ils.cat.biblio.records.merge',
908 Merges a group of records
909 @param auth The login session key
910 @param master The id of the record all other r
911 ecords should be merged into
912 @param records Array of records to be merged into the master record
913 @return 1 on success, Event on error.
918 my( $self, $conn, $auth, $master, $records ) = @_;
919 my( $reqr, $evt ) = $U->checkses($auth);
921 my $editor = new_editor( requestor => $reqr, xact => 1 );
922 my $v = OpenILS::Application::Cat::Merge::merge_records($editor, $master, $records);
931 # ---------------------------------------------------------------------------
932 # ---------------------------------------------------------------------------
934 # returns true if the given title (id) has no un-deleted
937 my( $editor, $rid ) = @_;
939 return 0 if $rid == OILS_PRECAT_RECORD;
941 my $cnlist = $editor->search_asset_call_number(
942 { record => $rid, deleted => 'f' }, { idlist => 1 } );
943 return 1 unless @$cnlist;
945 for my $cn (@$cnlist) {
946 my $copylist = $editor->search_asset_copy(
948 { call_number => $cn, deleted => 'f' },
951 return 0 if @$copylist; # false if we find any copies
958 __PACKAGE__->register_method(
959 method => "fleshed_volume_update",
960 api_name => "open-ils.cat.asset.volume.fleshed.batch.update",);
962 __PACKAGE__->register_method(
963 method => "fleshed_volume_update",
964 api_name => "open-ils.cat.asset.volume.fleshed.batch.update.override",);
966 sub fleshed_volume_update {
967 my( $self, $conn, $auth, $volumes, $delete_stats ) = @_;
968 my( $reqr, $evt ) = $U->checkses($auth);
971 my $override = ($self->api_name =~ /override/);
972 my $editor = new_editor( requestor => $reqr, xact => 1 );
974 for my $vol (@$volumes) {
975 $logger->info("vol-update: investigating volume ".$vol->id);
977 $vol->editor($reqr->id);
978 $vol->edit_date('now');
980 my $copies = $vol->copies;
983 $vol->editor($editor->requestor->id);
984 $vol->edit_date('now');
986 if( $vol->isdeleted ) {
988 $logger->info("vol-update: deleting volume");
989 my $cs = $editor->search_asset_copy(
990 { call_number => $vol->id, deleted => 'f' } );
991 return OpenILS::Event->new(
992 'VOLUME_NOT_EMPTY', payload => $vol->id ) if @$cs;
995 return $editor->event unless
996 $editor->update_asset_call_number($vol);
999 } elsif( $vol->isnew ) {
1000 $logger->info("vol-update: creating volume");
1001 $evt = create_volume( $override, $editor, $vol );
1002 return $evt if $evt;
1004 } elsif( $vol->ischanged ) {
1005 $logger->info("vol-update: update volume");
1006 $evt = update_volume($vol, $editor);
1007 return $evt if $evt;
1010 # now update any attached copies
1011 if( @$copies and !$vol->isdeleted ) {
1012 $_->call_number($vol->id) for @$copies;
1013 $evt = update_fleshed_copies( $editor, $override, $vol, $copies, $delete_stats );
1014 return $evt if $evt;
1019 return scalar(@$volumes);
1028 return $evt if ( $evt = org_cannot_have_vols($editor, $vol->owning_lib) );
1030 my $vols = $editor->search_asset_call_number( {
1031 owning_lib => $vol->owning_lib,
1032 record => $vol->record,
1033 label => $vol->label,
1038 # There exists a different volume in the DB with the same properties
1039 return OpenILS::Event->new('VOLUME_LABEL_EXISTS', payload => $vol->id)
1040 if grep { $_->id ne $vol->id } @$vols;
1042 return $editor->event unless $editor->update_asset_call_number($vol);
1049 my( $vol, $copy ) = @_;
1050 my $org = $vol->owning_lib;
1051 if( $vol->id == OILS_PRECAT_CALL_NUMBER ) {
1052 $org = ref($copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
1054 $logger->debug("using copy perm org $org");
1059 # this does the actual work
1060 sub update_fleshed_copies {
1061 my( $editor, $override, $vol, $copies, $delete_stats ) = @_;
1064 my $fetchvol = ($vol) ? 0 : 1;
1067 $cache{$vol->id} = $vol if $vol;
1069 for my $copy (@$copies) {
1071 my $copyid = $copy->id;
1072 $logger->info("vol-update: inspecting copy $copyid");
1074 if( !($vol = $cache{$copy->call_number}) ) {
1075 $vol = $cache{$copy->call_number} =
1076 $editor->retrieve_asset_call_number($copy->call_number);
1077 return $editor->event unless $vol;
1080 return $editor->event unless
1081 $editor->allowed('UPDATE_COPY', copy_perm_org($vol, $copy));
1083 $copy->editor($editor->requestor->id);
1084 $copy->edit_date('now');
1086 $copy->status( $copy->status->id ) if ref($copy->status);
1087 $copy->location( $copy->location->id ) if ref($copy->location);
1088 $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
1090 my $sc_entries = $copy->stat_cat_entries;
1091 $copy->clear_stat_cat_entries;
1093 if( $copy->isdeleted ) {
1094 $evt = delete_copy($editor, $override, $vol, $copy);
1095 return $evt if $evt;
1097 } elsif( $copy->isnew ) {
1098 $evt = create_copy( $editor, $vol, $copy );
1099 return $evt if $evt;
1101 } elsif( $copy->ischanged ) {
1103 $evt = update_copy( $editor, $override, $vol, $copy );
1104 return $evt if $evt;
1107 $copy->stat_cat_entries( $sc_entries );
1108 $evt = update_copy_stat_entries($editor, $copy, $delete_stats);
1109 return $evt if $evt;
1112 $logger->debug("vol-update: done updating copy batch");
1117 sub fix_copy_price {
1119 my $p = $copy->price || 0;
1123 my $d = $copy->deposit_amount || 0;
1125 $copy->deposit_amount($d);
1130 my( $editor, $override, $vol, $copy ) = @_;
1133 my $org = (ref $copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
1134 return $evt if ( $evt = org_cannot_have_vols($editor, $org) );
1136 $logger->info("vol-update: updating copy ".$copy->id);
1137 my $orig_copy = $editor->retrieve_asset_copy($copy->id);
1138 my $orig_vol = $editor->retrieve_asset_call_number($copy->call_number);
1140 $copy->editor($editor->requestor->id);
1141 $copy->edit_date('now');
1143 $copy->age_protect( $copy->age_protect->id )
1144 if ref $copy->age_protect;
1146 fix_copy_price($copy);
1148 return $editor->event unless $editor->update_asset_copy($copy);
1149 return remove_empty_objects($editor, $override, $orig_vol);
1153 sub remove_empty_objects {
1154 my( $editor, $override, $vol ) = @_;
1155 if( title_is_empty($editor, $vol->record) ) {
1157 # disable the TITLE_LAST_COPY event for now
1161 # delete this volume if it's not already marked as deleted
1162 unless( $U->is_true($vol->deleted) || $vol->isdeleted ) {
1164 $vol->editor($editor->requestor->id);
1165 $vol->edit_date('now');
1166 $editor->update_asset_call_number($vol) or return $editor->event;
1169 # then delete the record this volume points to
1170 my $rec = $editor->retrieve_biblio_record_entry($vol->record)
1171 or return $editor->event;
1173 unless( $U->is_true($rec->deleted) ) {
1176 $editor->update_biblio_record_entry($rec) or return $editor->event;
1180 return OpenILS::Event->new('TITLE_LAST_COPY', payload => $vol->record );
1189 my( $editor, $override, $vol, $copy ) = @_;
1191 my $stat = $U->copy_status($copy->status)->id;
1194 return OpenILS::Event->new('COPY_DELETE_WARNING', payload => $copy->id )
1195 if $stat == OILS_COPY_STATUS_CHECKED_OUT or
1196 $stat == OILS_COPY_STATUS_IN_TRANSIT or
1197 $stat == OILS_COPY_STATUS_ON_HOLDS_SHELF or
1198 $stat == OILS_COPY_STATUS_ILL;
1201 $logger->info("vol-update: deleting copy ".$copy->id);
1202 $copy->deleted('t');
1204 $copy->editor($editor->requestor->id);
1205 $copy->edit_date('now');
1206 $editor->update_asset_copy($copy) or return $editor->event;
1208 # Delete any open transits for this copy
1209 my $transits = $editor->search_action_transit_copy(
1210 { target_copy=>$copy->id, dest_recv_time => undef } );
1212 for my $t (@$transits) {
1213 $editor->delete_action_transit_copy($t)
1214 or return $editor->event;
1217 return remove_empty_objects($editor, $override, $vol);
1222 my( $editor, $vol, $copy ) = @_;
1224 my $existing = $editor->search_asset_copy(
1225 { barcode => $copy->barcode, deleted => 'f' } );
1227 return OpenILS::Event->new('ITEM_BARCODE_EXISTS') if @$existing;
1230 my $org = (ref $copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
1231 return $evt if ( $evt = org_cannot_have_vols($editor, $org) );
1234 $copy->creator($editor->requestor->id);
1235 $copy->create_date('now');
1236 fix_copy_price($copy);
1238 $editor->create_asset_copy($copy) or return $editor->event;
1242 # if 'delete_stats' is true, the copy->stat_cat_entries data is
1243 # treated as the authoritative list for the copy. existing entries
1244 # that are not in said list will be deleted from the DB
1245 sub update_copy_stat_entries {
1246 my( $editor, $copy, $delete_stats ) = @_;
1248 return undef if $copy->isdeleted;
1249 return undef unless $copy->ischanged or $copy->isnew;
1252 my $entries = $copy->stat_cat_entries;
1254 if( $delete_stats ) {
1255 $entries = ($entries and @$entries) ? $entries : [];
1257 return undef unless ($entries and @$entries);
1260 my $maps = $editor->search_asset_stat_cat_entry_copy_map({owning_copy=>$copy->id});
1263 # if there is no stat cat entry on the copy who's id matches the
1264 # current map's id, remove the map from the database
1265 for my $map (@$maps) {
1266 if(! grep { $_->id == $map->stat_cat_entry } @$entries ) {
1268 $logger->info("copy update found stale ".
1269 "stat cat entry map ".$map->id. " on copy ".$copy->id);
1271 $editor->delete_asset_stat_cat_entry_copy_map($map)
1272 or return $editor->event;
1277 # go through the stat cat update/create process
1278 for my $entry (@$entries) {
1281 # if this link already exists in the DB, don't attempt to re-create it
1282 next if( grep{$_->stat_cat_entry == $entry->id} @$maps );
1284 my $new_map = Fieldmapper::asset::stat_cat_entry_copy_map->new();
1286 my $sc = ref($entry->stat_cat) ? $entry->stat_cat->id : $entry->stat_cat;
1288 $new_map->stat_cat( $sc );
1289 $new_map->stat_cat_entry( $entry->id );
1290 $new_map->owning_copy( $copy->id );
1292 $editor->create_asset_stat_cat_entry_copy_map($new_map)
1293 or return $editor->event;
1295 $logger->info("copy update created new stat cat entry map ".$editor->data);
1303 my( $override, $editor, $vol ) = @_;
1306 return $evt if ( $evt = org_cannot_have_vols($editor, $vol->owning_lib) );
1308 # first lets see if there are any collisions
1309 my $vols = $editor->search_asset_call_number( {
1310 owning_lib => $vol->owning_lib,
1311 record => $vol->record,
1312 label => $vol->label,
1320 $label = $vol->label;
1322 return OpenILS::Event->new(
1323 'VOLUME_LABEL_EXISTS', payload => $vol->id);
1327 # create a temp label so we can create the volume, then de-dup it
1328 $vol->label( '__SYSTEM_TMP_'.time) if $label;
1330 $vol->creator($editor->requestor->id);
1331 $vol->create_date('now');
1332 $vol->editor($editor->requestor->id);
1333 $vol->edit_date('now');
1336 $editor->create_asset_call_number($vol) or return $editor->event;
1339 # now restore the label and merge into the existing record
1340 $vol->label($label);
1342 OpenILS::Application::Cat::Merge::merge_volumes($editor, [$vol], $$vols[0]);
1343 return $evt if $evt;
1350 __PACKAGE__->register_method (
1351 method => 'batch_volume_transfer',
1352 api_name => 'open-ils.cat.asset.volume.batch.transfer',
1355 __PACKAGE__->register_method (
1356 method => 'batch_volume_transfer',
1357 api_name => 'open-ils.cat.asset.volume.batch.transfer.override',
1361 sub batch_volume_transfer {
1362 my( $self, $conn, $auth, $args ) = @_;
1365 my $rec = $$args{docid};
1366 my $o_lib = $$args{lib};
1367 my $vol_ids = $$args{volumes};
1369 my $override = 1 if $self->api_name =~ /override/;
1371 $logger->info("merge: transferring volumes to lib=$o_lib and record=$rec");
1373 my $e = new_editor(authtoken => $auth, xact =>1);
1374 return $e->event unless $e->checkauth;
1375 return $e->event unless $e->allowed('VOLUME_UPDATE', $o_lib);
1377 my $dorg = $e->retrieve_actor_org_unit($o_lib)
1378 or return $e->event;
1380 my $ou_type = $e->retrieve_actor_org_unit_type($dorg->ou_type)
1381 or return $e->event;
1383 return $evt if ( $evt = org_cannot_have_vols($e, $o_lib) );
1385 my $vols = $e->batch_retrieve_asset_call_number($vol_ids);
1388 for my $vol (@$vols) {
1390 # if we've already looked at this volume, go to the next
1391 next if !$vol or grep { $vol->id == $_ } @seen;
1393 # grab all of the volumes in the list that have
1394 # the same label so they can be merged
1395 my @all = grep { $_->label eq $vol->label } @$vols;
1397 # take note of the fact that we've looked at this set of volumes
1398 push( @seen, $_->id ) for @all;
1400 # for each volume, see if there are any copies that have a
1401 # remote circ_lib (circ_lib != vol->owning_lib and != $o_lib ).
1403 unless( $override ) {
1406 $logger->debug("merge: searching for copies with remote circ_lib for volume ".$v->id);
1408 call_number => $v->id,
1409 circ_lib => { "not in" => [ $o_lib, $v->owning_lib ] },
1413 my $copies = $e->search_asset_copy($args, {idlist=>1});
1415 # if the copy's circ_lib matches the destination lib,
1417 return OpenILS::Event->new('COPY_REMOTE_CIRC_LIB') if @$copies;
1421 # see if there is a volume at the destination lib that
1422 # already has the requested label
1423 my $existing_vol = $e->search_asset_call_number(
1425 label => $vol->label,
1427 owning_lib =>$o_lib,
1432 if( $existing_vol ) {
1434 if( grep { $_->id == $existing_vol->id } @all ) {
1435 # this volume is already accounted for in our list of volumes to merge
1436 $existing_vol = undef;
1439 # this volume exists on the destination record/owning_lib and must
1440 # be used as the destination for merging
1441 $logger->debug("merge: volume already exists at destination record: ".
1442 $existing_vol->id.' : '.$existing_vol->label) if $existing_vol;
1446 if( @all > 1 || $existing_vol ) {
1447 $logger->info("merge: found collisions in volume transfer");
1448 my @args = ($e, \@all);
1449 @args = ($e, \@all, $existing_vol) if $existing_vol;
1450 ($vol, $evt) = OpenILS::Application::Cat::Merge::merge_volumes(@args);
1451 return $evt if $evt;
1454 if( !$existing_vol ) {
1456 $vol->owning_lib($o_lib);
1458 $vol->editor($e->requestor->id);
1459 $vol->edit_date('now');
1461 $logger->info("merge: updating volume ".$vol->id);
1462 $e->update_asset_call_number($vol) or return $e->event;
1465 $logger->info("merge: bypassing volume update because existing volume used as target");
1468 # regardless of what volume was used as the destination,
1469 # update any copies that have moved over to the new lib
1470 my $copies = $e->search_asset_copy({call_number=>$vol->id, deleted => 'f'});
1472 # update circ lib on the copies - make this a method flag?
1473 for my $copy (@$copies) {
1474 next if $copy->circ_lib == $o_lib;
1475 $logger->info("merge: transfer moving circ lib on copy ".$copy->id);
1476 $copy->circ_lib($o_lib);
1477 $copy->editor($e->requestor->id);
1478 $copy->edit_date('now');
1479 $e->update_asset_copy($copy) or return $e->event;
1482 # Now see if any empty records need to be deleted after all of this
1484 $evt = remove_empty_objects($e, $override, $_);
1485 return $evt if $evt;
1489 $logger->info("merge: transfer succeeded");
1496 sub org_cannot_have_vols {
1500 my $org = $e->retrieve_actor_org_unit($org_id)
1501 or return $e->event;
1503 my $ou_type = $e->retrieve_actor_org_unit_type($org->ou_type)
1504 or return $e->event;
1506 return OpenILS::Event->new('ORG_CANNOT_HAVE_VOLS')
1507 unless $U->is_true($ou_type->can_have_vols);
1515 __PACKAGE__->register_method(
1516 api_name => 'open-ils.cat.call_number.find_or_create',
1517 method => 'find_or_create_volume',
1520 sub find_or_create_volume {
1521 my( $self, $conn, $auth, $label, $record_id, $org_id ) = @_;
1522 my $e = new_editor(authtoken=>$auth, xact=>1);
1523 return $e->die_event unless $e->checkauth;
1525 my $vol = $e->search_asset_call_number(
1526 {label => $label, record => $record_id, owning_lib => $org_id, deleted => 'f'},
1530 # If the volume exists, return the ID
1531 if( $vol ) { $e->rollback; return $vol; }
1533 # -----------------------------------------------------------------
1534 # Otherwise, create a new volume with the given attributes
1535 # -----------------------------------------------------------------
1537 return $e->die_event unless $e->allowed('VOLUME_UPDATE', $org_id);
1539 $vol = Fieldmapper::asset::call_number->new;
1540 $vol->owning_lib($org_id);
1541 $vol->label($label);
1542 $vol->record($record_id);
1543 $vol->creator($e->requestor->id);
1544 $vol->create_date('now');
1545 $vol->editor($e->requestor->id);
1546 $vol->edit_date('now');
1548 $e->create_asset_call_number($vol) or return $e->die_event;