1 use strict; use warnings;
2 package OpenILS::Application::Cat;
3 use OpenILS::Application::AppUtils;
4 use OpenILS::Application;
5 use OpenILS::Application::Cat::Utils;
6 use OpenILS::Application::Cat::Merge;
7 use base qw/OpenILS::Application/;
8 use Time::HiRes qw(time);
9 use OpenSRF::EX qw(:try);
10 use OpenSRF::Utils::JSON;
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/;
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 ) = @_;
58 return $marctemplates{$type} if defined($marctemplates{$type});
59 $marctemplates{$type} = _load_marc_template($type);
60 return $marctemplates{$type};
63 __PACKAGE__->register_method(
64 method => 'fetch_marc_template_types',
65 api_name => 'open-ils.cat.marc_template.types.retrieve'
68 my $marc_template_files;
70 sub fetch_marc_template_types {
71 my( $self, $conn ) = @_;
72 __load_marc_templates();
73 return [ keys %$marc_template_files ];
76 sub __load_marc_templates {
77 return if $marc_template_files;
78 if(!$conf) { $conf = OpenSRF::Utils::SettingsClient->new; }
80 $marc_template_files = $conf->config_value(
81 "apps", "open-ils.cat","app_settings", "marctemplates" );
83 $logger->info("Loaded marc templates: " . Dumper($marc_template_files));
86 sub _load_marc_template {
89 __load_marc_templates();
91 my $template = $$marc_template_files{$type};
92 open( F, $template ) or
93 throw OpenSRF::EX::ERROR ("Unable to open MARC template file: $template : $@");
97 my $xml = join('', @xml);
99 return XML::LibXML->new->parse_string($xml)->documentElement->toString;
103 sub bib_source_from_name {
105 $logger->debug("searching for bib source: $name");
109 my ($s) = grep { lc($_->source) eq lc($name) } @$__bib_sources;
116 __PACKAGE__->register_method(
117 method => 'fetch_bib_sources',
118 api_name => 'open-ils.cat.bib_sources.retrieve.all');
120 sub fetch_bib_sources {
121 $__bib_sources = new_editor()->retrieve_all_config_bib_source()
122 unless $__bib_sources;
123 return $__bib_sources;
128 __PACKAGE__->register_method(
129 method => "create_record_xml",
130 api_name => "open-ils.cat.biblio.record.xml.create.override",
131 signature => q/@see open-ils.cat.biblio.record.xml.create/);
133 __PACKAGE__->register_method(
134 method => "create_record_xml",
135 api_name => "open-ils.cat.biblio.record.xml.create",
137 Inserts a new biblio with the given XML
141 sub create_record_xml {
142 my( $self, $client, $login, $xml, $source ) = @_;
144 my $override = 1 if $self->api_name =~ /override/;
146 my( $user_obj, $evt ) = $U->checksesperm($login, 'CREATE_MARC');
149 $logger->activity("user ".$user_obj->id." creating new MARC record");
151 my $meth = $self->method_lookup("open-ils.cat.biblio.record.xml.import");
153 $meth = $self->method_lookup(
154 "open-ils.cat.biblio.record.xml.import.override") if $override;
156 my ($s) = $meth->run($login, $xml, $source);
162 __PACKAGE__->register_method(
163 method => "biblio_record_replace_marc",
164 api_name => "open-ils.cat.biblio.record.xml.update",
167 Updates the XML for a given biblio record.
168 This does not change any other aspect of the record entry
169 exception the XML, the editor, and the edit date.
170 @return The update record object
174 __PACKAGE__->register_method(
175 method => 'biblio_record_replace_marc',
176 api_name => 'open-ils.cat.biblio.record.marc.replace',
178 @param auth The authtoken
179 @param recid The record whose MARC we're replacing
180 @param newxml The new xml to use
184 __PACKAGE__->register_method(
185 method => 'biblio_record_replace_marc',
186 api_name => 'open-ils.cat.biblio.record.marc.replace.override',
187 signature => q/@see open-ils.cat.biblio.record.marc.replace/
190 sub biblio_record_replace_marc {
191 my( $self, $conn, $auth, $recid, $newxml, $source ) = @_;
193 warn "Updating MARC with xml\n$newxml\n";
195 my $e = new_editor(authtoken=>$auth, xact=>1);
196 return $e->die_event unless $e->checkauth;
197 return $e->die_event unless $e->allowed('CREATE_MARC');
199 my $rec = $e->retrieve_biblio_record_entry($recid)
200 or return $e->die_event;
202 my $fixtcn = 1 if $self->api_name =~ /replace/o;
204 # See if there is a different record in the database that has our TCN value
205 # If we're not updating the TCN, all we care about it the marcdoc
206 my $override = $self->api_name =~ /override/;
208 # XXX should .update even bother with the tcn_info if it's not going to replace it?
209 # there is the potential for returning a TCN_EXISTS event, even though no replacement happens
211 my( $tcn, $tsource, $marcdoc, $evt);
213 if($fixtcn or $override) {
215 ($tcn, $tsource, $marcdoc, $evt) =
216 _find_tcn_info($e, $newxml, $override, $recid);
220 $rec->tcn_value($tcn);
221 $rec->tcn_source($tsource);
225 $marcdoc = __make_marc_doc($newxml);
230 $rec->source(bib_source_from_name($source)) if $source;
231 $rec->editor($e->requestor->id);
232 $rec->edit_date('now');
233 $rec->marc( entityize( $marcdoc->documentElement->toString ) );
235 $logger->activity("user ".$e->requestor->id." replacing MARC for record $recid");
237 $e->update_biblio_record_entry($rec) or return $e->event;
240 $conn->respond_complete($rec);
244 'open-ils.ingest.full.biblio.record', $recid );
252 __PACKAGE__->register_method(
253 method => "biblio_record_xml_import",
254 api_name => "open-ils.cat.biblio.record.xml.import.override",
255 signature => q/@see open-ils.cat.biblio.record.xml.import/);
257 __PACKAGE__->register_method(
258 method => "biblio_record_xml_import",
259 api_name => "open-ils.cat.biblio.record.xml.import",
260 notes => <<" NOTES");
261 Takes a marcxml record and imports the record into the database. In this
262 case, the marcxml record is assumed to be a complete record (i.e. valid
263 MARC). The title control number is taken from (whichever comes first)
264 tags 001, 039[ab], 020a, 022a, 010, 035a and whichever does not already exist
266 user_session must have IMPORT_MARC permissions
270 sub biblio_record_xml_import {
271 my( $self, $client, $authtoken, $xml, $source, $auto_tcn) = @_;
273 my $override = 1 if $self->api_name =~ /override/;
274 my $e = new_editor(xact=>1, authtoken=>$authtoken);
275 return $e->die_event unless $e->checkauth;
276 return $e->die_event unless $e->allowed('IMPORT_MARC');
278 my( $evt, $tcn, $tcn_source, $marcdoc );
281 # auto_tcn forces a blank TCN value so the DB will have to generate one for us
282 $marcdoc = __make_marc_doc($xml);
284 ( $tcn, $tcn_source, $marcdoc, $evt ) = _find_tcn_info($e, $xml, $override);
288 $logger->info("user ".$e->requestor->id.
289 " creating new biblio entry with tcn=$tcn and tcn_source $tcn_source");
291 my $record = Fieldmapper::biblio::record_entry->new;
293 $record->source(bib_source_from_name($source)) if $source;
294 $record->tcn_source($tcn_source);
295 $record->tcn_value($tcn);
296 $record->creator($e->requestor->id);
297 $record->editor($e->requestor->id);
298 $record->create_date('now');
299 $record->edit_date('now');
300 $record->marc( entityize( $marcdoc->documentElement->toString ) );
302 $record = $e->create_biblio_record_entry($record) or return $e->die_event;
303 $logger->info("marc create/import created new record ".$record->id);
307 $logger->debug("Sending record off to be ingested and indexed");
309 $client->respond_complete($record);
313 'open-ils.ingest.full.biblio.record', $record->id );
318 sub __make_marc_doc {
320 my $marcxml = XML::LibXML->new->parse_string( $xml );
321 $marcxml->documentElement->setNamespace(
322 "http://www.loc.gov/MARC21/slim", "marc", 1 );
330 my $override = shift;
331 my $existing_rec = shift || 0;
334 my $marcxml = __make_marc_doc($xml);
336 my $xpath = '//marc:controlfield[@tag="001"]';
337 my $tcn = $marcxml->documentElement->findvalue($xpath);
338 $logger->info("biblio import located 001 (tcn) value of $tcn");
340 $xpath = '//marc:controlfield[@tag="003"]';
341 my $tcn_source = $marcxml->documentElement->findvalue($xpath) || "System Local";
343 if(my $rec = _tcn_exists($editor, $tcn, $tcn_source, $existing_rec) ) {
346 $tcn = find_free_tcn( $marcxml, $editor, $existing_rec );
348 # if we're overriding, try to find a different TCN to use
351 # XXX Create ALLOW_ALT_TCN permission check support
353 $logger->info("tcn value $tcn already exists, attempting to override");
361 'OPEN_TCN_NOT_FOUND',
362 payload => $marcxml->toString())
368 $logger->warn("tcn value $origtcn already exists in import/create");
370 # otherwise, return event
376 'TCN_EXISTS', payload => {
386 return ($tcn, $tcn_source, $marcxml);
393 my $existing_rec = shift;
397 my $xpath = '//marc:datafield[@tag="039"]/subfield[@code="a"]';
398 my ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
399 $xpath = '//marc:datafield[@tag="039"]/subfield[@code="b"]';
400 my $tcn_source = $marcxml->documentElement->findvalue($xpath) || "System Local";
402 if(_tcn_exists($editor, $tcn, $tcn_source, $existing_rec)) {
410 $xpath = '//marc:datafield[@tag="020"]/subfield[@code="a"]';
411 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
412 $tcn_source = "ISBN";
413 if(_tcn_exists($editor, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
417 $xpath = '//marc:datafield[@tag="022"]/subfield[@code="a"]';
418 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
419 $tcn_source = "ISSN";
420 if(_tcn_exists($editor, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
424 $xpath = '//marc:datafield[@tag="010"]';
425 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
426 $tcn_source = "LCCN";
427 if(_tcn_exists($editor, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
431 $xpath = '//marc:datafield[@tag="035"]/subfield[@code="a"]';
432 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
433 $tcn_source = "System Legacy";
434 if(_tcn_exists($editor, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
437 $marcxml->documentElement->removeChild(
438 $marcxml->documentElement->findnodes( '//datafield[@tag="035"]' )
443 return undef unless $tcn;
446 my $df = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'datafield');
447 $df->setAttribute( tag => '039' );
448 $df->setAttribute( ind1 => ' ' );
449 $df->setAttribute( ind2 => ' ' );
450 $marcxml->documentElement->appendChild( $df );
452 my $sfa = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'subfield');
453 $sfa->setAttribute( code => 'a' );
454 $sfa->appendChild( $marcxml->createTextNode( $tcn ) );
455 $df->appendChild( $sfa );
457 my $sfb = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'subfield');
458 $sfb->setAttribute( code => 'b' );
459 $sfb->appendChild( $marcxml->createTextNode( $tcn_source ) );
460 $df->appendChild( $sfb );
472 my $existing_rec = shift || 0;
474 if(!$tcn) {return 0;}
476 $logger->debug("tcn_exists search for tcn $tcn and source $source and id $existing_rec");
478 # XXX why does the source matter?
479 # my $req = $session->request(
480 # { tcn_value => $tcn, tcn_source => $source, deleted => 'f' } );
482 my $recs = $editor->search_biblio_record_entry(
483 {tcn_value => $tcn, deleted => 'f', id => {'!=' => $existing_rec}}, {idlist =>1});
486 $logger->debug("_tcn_exists is true for tcn : $tcn ($source)");
490 $logger->debug("_tcn_exists is false for tcn : $tcn ($source)");
495 __PACKAGE__->register_method(
496 method => "biblio_record_record_metadata",
497 api_name => "open-ils.cat.biblio.record.metadata.retrieve",
498 argc => 1, #(session_id, biblio_tree )
499 notes => "Walks the tree and commits any changed nodes " .
500 "adds any new nodes, and deletes any deleted nodes",
503 sub biblio_record_record_metadata {
504 my( $self, $client, $authtoken, $ids ) = @_;
506 return [] unless $ids and @$ids;
508 my $editor = new_editor(authtoken => $authtoken);
509 return $editor->event unless $editor->checkauth;
510 return $editor->event unless $editor->allowed('VIEW_USER');
515 return $editor->event unless
516 my $rec = $editor->retrieve_biblio_record_entry($_);
517 $rec->creator($editor->retrieve_actor_user($rec->creator));
518 $rec->editor($editor->retrieve_actor_user($rec->editor));
519 $rec->clear_marc; # slim the record down
520 push( @results, $rec );
528 __PACKAGE__->register_method(
529 method => "biblio_record_marc_cn",
530 api_name => "open-ils.cat.biblio.record.marc_cn.retrieve",
531 argc => 1, #(bib id )
534 sub biblio_record_marc_cn {
535 my( $self, $client, $id ) = @_;
537 my $session = OpenSRF::AppSession->create("open-ils.cstore");
539 ->request("open-ils.cstore.direct.biblio.record_entry.retrieve", $id )
543 my $doc = XML::LibXML->new->parse_string($marc);
544 $doc->documentElement->setNamespace( "http://www.loc.gov/MARC21/slim", "marc", 1 );
547 for my $tag ( qw/050 055 060 070 080 082 086 088 090 092 096 098 099/ ) {
548 my @node = $doc->findnodes("//marc:datafield[\@tag='$tag']");
550 my $cn = $x->findvalue("marc:subfield[\@code='a' or \@code='b']");
551 push @res, {$tag => $cn} if ($cn);
558 sub _get_id_by_userid {
563 my $session = OpenSRF::AppSession->create( "open-ils.cstore" );
564 my $request = $session->request(
565 "open-ils.cstore.direct.actor.user.search.atomic", { usrname => \@users } );
567 $request->wait_complete;
568 my $response = $request->recv();
569 if(!$request->complete) {
570 throw OpenSRF::EX::ERROR ("no response from cstore on user retrieve");
573 if(UNIVERSAL::isa( $response, "Error")){
574 throw $response ($response);
577 for my $u (@{$response->content}) {
583 $session->disconnect;
590 # commits metadata objects to the db
591 sub _update_record_metadata {
593 my ($session, @docs ) = @_;
595 for my $doc (@docs) {
597 my $user_obj = $doc->{user};
598 my $docid = $doc->{docid};
600 warn "Updating metata for doc $docid\n";
602 my $request = $session->request(
603 "open-ils.storage.direct.biblio.record_entry.retrieve", $docid );
604 my $record = $request->gather(1);
606 warn "retrieved record\n";
607 my ($id) = _get_id_by_userid($user_obj->usrname);
609 warn "got $id from _get_id_by_userid\n";
610 $record->editor($id);
612 warn "Grabbed the record, updating and moving on\n";
614 $request = $session->request(
615 "open-ils.storage.direct.biblio.record_entry.update", $record );
619 warn "committing metarecord update\n";
626 __PACKAGE__->register_method(
627 method => "orgs_for_title",
628 api_name => "open-ils.cat.actor.org_unit.retrieve_by_title"
632 my( $self, $client, $record_id ) = @_;
634 my $vols = $apputils->simple_scalar_request(
636 "open-ils.cstore.direct.asset.call_number.search.atomic",
637 { record => $record_id, deleted => 'f' });
639 my $orgs = { map {$_->owning_lib => 1 } @$vols };
640 return [ keys %$orgs ];
644 __PACKAGE__->register_method(
645 method => "retrieve_copies",
646 api_name => "open-ils.cat.asset.copy_tree.retrieve");
648 __PACKAGE__->register_method(
649 method => "retrieve_copies",
650 api_name => "open-ils.cat.asset.copy_tree.global.retrieve");
652 # user_session may be null/undef
653 sub retrieve_copies {
655 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
657 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
661 warn " $$ retrieving copy tree for orgs @org_ids and doc $docid at " . time() . "\n";
663 # grabbing copy trees should be available for everyone..
664 if(!@org_ids and $user_session) {
666 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
667 @org_ids = ($user_obj->home_ou);
670 if( $self->api_name =~ /global/ ) {
671 warn "performing global copy_tree search for $docid\n";
672 return _build_volume_list( { record => $docid, deleted => 'f' } );
677 for my $orgid (@org_ids) {
678 my $vols = _build_volume_list(
679 { record => $docid, owning_lib => $orgid, deleted => 'f' } );
680 warn "Volumes built for org $orgid\n";
681 push( @all_vols, @$vols );
684 warn " $$ Finished copy_tree at " . time() . "\n";
692 sub _build_volume_list {
693 my $search_hash = shift;
695 $search_hash->{deleted} = 'f';
696 my $e = new_editor();
698 my $vols = $e->search_asset_call_number($search_hash);
702 for my $volume (@$vols) {
704 my $copies = $e->search_asset_copy(
705 { call_number => $volume->id , deleted => 'f' });
707 $copies = [ sort { $a->barcode cmp $b->barcode } @$copies ];
709 for my $c (@$copies) {
710 if( $c->status == OILS_COPY_STATUS_CHECKED_OUT ) {
712 $e->search_action_circulation(
714 { target_copy => $c->id },
716 order_by => { circ => 'xact_start desc' },
725 $volume->copies($copies);
726 push( @volumes, $volume );
729 #$session->disconnect();
735 __PACKAGE__->register_method(
736 method => "fleshed_copy_update",
737 api_name => "open-ils.cat.asset.copy.fleshed.batch.update",);
739 __PACKAGE__->register_method(
740 method => "fleshed_copy_update",
741 api_name => "open-ils.cat.asset.copy.fleshed.batch.update.override",);
744 sub fleshed_copy_update {
745 my( $self, $conn, $auth, $copies, $delete_stats ) = @_;
746 return 1 unless ref $copies;
747 my( $reqr, $evt ) = $U->checkses($auth);
749 my $editor = new_editor(requestor => $reqr, xact => 1);
750 my $override = $self->api_name =~ /override/;
751 $evt = update_fleshed_copies($editor, $override, undef, $copies, $delete_stats);
753 $logger->info("fleshed copy update failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
758 $logger->info("fleshed copy update successfully updated ".scalar(@$copies)." copies");
763 __PACKAGE__->register_method(
765 api_name => 'open-ils.cat.biblio.records.merge',
767 Merges a group of records
768 @param auth The login session key
769 @param master The id of the record all other r
770 ecords should be merged into
771 @param records Array of records to be merged into the master record
772 @return 1 on success, Event on error.
777 my( $self, $conn, $auth, $master, $records ) = @_;
778 my( $reqr, $evt ) = $U->checkses($auth);
780 my $editor = new_editor( requestor => $reqr, xact => 1 );
781 my $v = OpenILS::Application::Cat::Merge::merge_records($editor, $master, $records);
790 # ---------------------------------------------------------------------------
791 # ---------------------------------------------------------------------------
793 # returns true if the given title (id) has no un-deleted
796 my( $editor, $rid ) = @_;
798 return 0 if $rid == OILS_PRECAT_RECORD;
800 my $cnlist = $editor->search_asset_call_number(
801 { record => $rid, deleted => 'f' }, { idlist => 1 } );
802 return 1 unless @$cnlist;
804 for my $cn (@$cnlist) {
805 my $copylist = $editor->search_asset_copy(
807 { call_number => $cn, deleted => 'f' },
810 return 0 if @$copylist; # false if we find any copies
817 __PACKAGE__->register_method(
818 method => "fleshed_volume_update",
819 api_name => "open-ils.cat.asset.volume.fleshed.batch.update",);
821 __PACKAGE__->register_method(
822 method => "fleshed_volume_update",
823 api_name => "open-ils.cat.asset.volume.fleshed.batch.update.override",);
825 sub fleshed_volume_update {
826 my( $self, $conn, $auth, $volumes, $delete_stats ) = @_;
827 my( $reqr, $evt ) = $U->checkses($auth);
830 my $override = ($self->api_name =~ /override/);
831 my $editor = new_editor( requestor => $reqr, xact => 1 );
833 for my $vol (@$volumes) {
834 $logger->info("vol-update: investigating volume ".$vol->id);
836 $vol->editor($reqr->id);
837 $vol->edit_date('now');
839 my $copies = $vol->copies;
842 $vol->editor($editor->requestor->id);
843 $vol->edit_date('now');
845 if( $vol->isdeleted ) {
847 $logger->info("vol-update: deleting volume");
848 my $cs = $editor->search_asset_copy(
849 { call_number => $vol->id, deleted => 'f' } );
850 return OpenILS::Event->new(
851 'VOLUME_NOT_EMPTY', payload => $vol->id ) if @$cs;
854 return $editor->event unless
855 $editor->update_asset_call_number($vol);
858 } elsif( $vol->isnew ) {
859 $logger->info("vol-update: creating volume");
860 $evt = create_volume( $override, $editor, $vol );
863 } elsif( $vol->ischanged ) {
864 $logger->info("vol-update: update volume");
865 $evt = update_volume($vol, $editor);
869 # now update any attached copies
870 if( @$copies and !$vol->isdeleted ) {
871 $_->call_number($vol->id) for @$copies;
872 $evt = update_fleshed_copies( $editor, $override, $vol, $copies, $delete_stats );
878 return scalar(@$volumes);
887 return $evt if ( $evt = org_cannot_have_vols($editor, $vol->owning_lib) );
889 my $vols = $editor->search_asset_call_number( {
890 owning_lib => $vol->owning_lib,
891 record => $vol->record,
892 label => $vol->label,
897 # There exists a different volume in the DB with the same properties
898 return OpenILS::Event->new('VOLUME_LABEL_EXISTS', payload => $vol->id)
899 if grep { $_->id ne $vol->id } @$vols;
901 return $editor->event unless $editor->update_asset_call_number($vol);
908 my( $vol, $copy ) = @_;
909 my $org = $vol->owning_lib;
910 if( $vol->id == OILS_PRECAT_CALL_NUMBER ) {
911 $org = ref($copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
913 $logger->debug("using copy perm org $org");
918 # this does the actual work
919 sub update_fleshed_copies {
920 my( $editor, $override, $vol, $copies, $delete_stats ) = @_;
923 my $fetchvol = ($vol) ? 0 : 1;
926 $cache{$vol->id} = $vol if $vol;
928 for my $copy (@$copies) {
930 my $copyid = $copy->id;
931 $logger->info("vol-update: inspecting copy $copyid");
933 if( !($vol = $cache{$copy->call_number}) ) {
934 $vol = $cache{$copy->call_number} =
935 $editor->retrieve_asset_call_number($copy->call_number);
936 return $editor->event unless $vol;
939 return $editor->event unless
940 $editor->allowed('UPDATE_COPY', copy_perm_org($vol, $copy));
942 $copy->editor($editor->requestor->id);
943 $copy->edit_date('now');
945 $copy->status( $copy->status->id ) if ref($copy->status);
946 $copy->location( $copy->location->id ) if ref($copy->location);
947 $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
949 my $sc_entries = $copy->stat_cat_entries;
950 $copy->clear_stat_cat_entries;
952 if( $copy->isdeleted ) {
953 $evt = delete_copy($editor, $override, $vol, $copy);
956 } elsif( $copy->isnew ) {
957 $evt = create_copy( $editor, $vol, $copy );
960 } elsif( $copy->ischanged ) {
962 $evt = update_copy( $editor, $override, $vol, $copy );
966 $copy->stat_cat_entries( $sc_entries );
967 $evt = update_copy_stat_entries($editor, $copy, $delete_stats);
971 $logger->debug("vol-update: done updating copy batch");
978 my $p = $copy->price || 0;
982 my $d = $copy->deposit_amount || 0;
984 $copy->deposit_amount($d);
989 my( $editor, $override, $vol, $copy ) = @_;
992 my $org = (ref $copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
993 return $evt if ( $evt = org_cannot_have_vols($editor, $org) );
995 $logger->info("vol-update: updating copy ".$copy->id);
996 my $orig_copy = $editor->retrieve_asset_copy($copy->id);
997 my $orig_vol = $editor->retrieve_asset_call_number($copy->call_number);
999 $copy->editor($editor->requestor->id);
1000 $copy->edit_date('now');
1002 $copy->age_protect( $copy->age_protect->id )
1003 if ref $copy->age_protect;
1005 fix_copy_price($copy);
1007 return $editor->event unless $editor->update_asset_copy($copy);
1008 return remove_empty_objects($editor, $override, $orig_vol);
1012 sub remove_empty_objects {
1013 my( $editor, $override, $vol ) = @_;
1014 if( title_is_empty($editor, $vol->record) ) {
1016 # disable the TITLE_LAST_COPY event for now
1020 # delete this volume if it's not already marked as deleted
1021 unless( $U->is_true($vol->deleted) || $vol->isdeleted ) {
1023 $vol->editor($editor->requestor->id);
1024 $vol->edit_date('now');
1025 $editor->update_asset_call_number($vol) or return $editor->event;
1028 my $evt = delete_rec($editor, $vol->record);
1029 return $evt if $evt;
1032 return OpenILS::Event->new('TITLE_LAST_COPY', payload => $vol->record );
1040 __PACKAGE__->register_method (
1041 method => 'delete_bib_record',
1042 api_name => 'open-ils.cat.biblio.record_entry.delete');
1044 sub delete_bib_record {
1045 my($self, $conn, $auth, $rec_id) = @_;
1046 my $e = new_editor(xact=>1, authtoken=>$auth);
1047 return $e->die_event unless $e->checkauth;
1048 return $e->die_event unless $e->allowed('DELETE_RECORD');
1049 my $vols = $e->search_asset_call_number({record=>$rec_id, deleted=>'f'});
1050 return OpenILS::Event->new('RECORD_NOT_EMPTY', payload=>$rec_id) if @$vols;
1051 my $evt = delete_rec($e, $rec_id);
1052 if($evt) { $e->rollback; return $evt; }
1058 # marks a record as deleted
1060 my( $editor, $rec_id ) = @_;
1062 my $rec = $editor->retrieve_biblio_record_entry($rec_id)
1063 or return $editor->event;
1065 return undef if $U->is_true($rec->deleted);
1069 $rec->editor( $editor->requestor->id );
1070 $rec->edit_date('now');
1071 $editor->update_biblio_record_entry($rec) or return $editor->event;
1078 my( $editor, $override, $vol, $copy ) = @_;
1080 return $editor->event unless
1081 $editor->allowed('DELETE_COPY',copy_perm_org($vol, $copy));
1083 my $stat = $U->copy_status($copy->status)->id;
1086 return OpenILS::Event->new('COPY_DELETE_WARNING', payload => $copy->id )
1087 if $stat == OILS_COPY_STATUS_CHECKED_OUT or
1088 $stat == OILS_COPY_STATUS_IN_TRANSIT or
1089 $stat == OILS_COPY_STATUS_ON_HOLDS_SHELF or
1090 $stat == OILS_COPY_STATUS_ILL;
1093 $logger->info("vol-update: deleting copy ".$copy->id);
1094 $copy->deleted('t');
1096 $copy->editor($editor->requestor->id);
1097 $copy->edit_date('now');
1098 $editor->update_asset_copy($copy) or return $editor->event;
1100 # Delete any open transits for this copy
1101 my $transits = $editor->search_action_transit_copy(
1102 { target_copy=>$copy->id, dest_recv_time => undef } );
1104 for my $t (@$transits) {
1105 $editor->delete_action_transit_copy($t)
1106 or return $editor->event;
1109 return remove_empty_objects($editor, $override, $vol);
1114 my( $editor, $vol, $copy ) = @_;
1116 my $existing = $editor->search_asset_copy(
1117 { barcode => $copy->barcode, deleted => 'f' } );
1119 return OpenILS::Event->new('ITEM_BARCODE_EXISTS') if @$existing;
1121 # see if the volume this copy references is marked as deleted
1122 my $evol = $editor->retrieve_asset_call_number($copy->call_number)
1123 or return $editor->event;
1124 return OpenILS::Event->new('VOLUME_DELETED', vol => $evol->id)
1125 if $U->is_true($evol->deleted);
1128 my $org = (ref $copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
1129 return $evt if ( $evt = org_cannot_have_vols($editor, $org) );
1132 $copy->creator($editor->requestor->id);
1133 $copy->create_date('now');
1134 fix_copy_price($copy);
1136 $editor->create_asset_copy($copy) or return $editor->event;
1140 # if 'delete_stats' is true, the copy->stat_cat_entries data is
1141 # treated as the authoritative list for the copy. existing entries
1142 # that are not in said list will be deleted from the DB
1143 sub update_copy_stat_entries {
1144 my( $editor, $copy, $delete_stats ) = @_;
1146 return undef if $copy->isdeleted;
1147 return undef unless $copy->ischanged or $copy->isnew;
1150 my $entries = $copy->stat_cat_entries;
1152 if( $delete_stats ) {
1153 $entries = ($entries and @$entries) ? $entries : [];
1155 return undef unless ($entries and @$entries);
1158 my $maps = $editor->search_asset_stat_cat_entry_copy_map({owning_copy=>$copy->id});
1161 # if there is no stat cat entry on the copy who's id matches the
1162 # current map's id, remove the map from the database
1163 for my $map (@$maps) {
1164 if(! grep { $_->id == $map->stat_cat_entry } @$entries ) {
1166 $logger->info("copy update found stale ".
1167 "stat cat entry map ".$map->id. " on copy ".$copy->id);
1169 $editor->delete_asset_stat_cat_entry_copy_map($map)
1170 or return $editor->event;
1175 # go through the stat cat update/create process
1176 for my $entry (@$entries) {
1179 # if this link already exists in the DB, don't attempt to re-create it
1180 next if( grep{$_->stat_cat_entry == $entry->id} @$maps );
1182 my $new_map = Fieldmapper::asset::stat_cat_entry_copy_map->new();
1184 my $sc = ref($entry->stat_cat) ? $entry->stat_cat->id : $entry->stat_cat;
1186 $new_map->stat_cat( $sc );
1187 $new_map->stat_cat_entry( $entry->id );
1188 $new_map->owning_copy( $copy->id );
1190 $editor->create_asset_stat_cat_entry_copy_map($new_map)
1191 or return $editor->event;
1193 $logger->info("copy update created new stat cat entry map ".$editor->data);
1201 my( $override, $editor, $vol ) = @_;
1204 return $evt if ( $evt = org_cannot_have_vols($editor, $vol->owning_lib) );
1206 # see if the record this volume references is marked as deleted
1207 my $rec = $editor->retrieve_biblio_record_entry($vol->record)
1208 or return $editor->event;
1209 return OpenILS::Event->new('BIB_RECORD_DELETED', rec => $rec->id)
1210 if $U->is_true($rec->deleted);
1212 # first lets see if there are any collisions
1213 my $vols = $editor->search_asset_call_number( {
1214 owning_lib => $vol->owning_lib,
1215 record => $vol->record,
1216 label => $vol->label,
1223 # we've found an exising volume
1225 $label = $vol->label;
1227 return OpenILS::Event->new(
1228 'VOLUME_LABEL_EXISTS', payload => $vol->id);
1232 # create a temp label so we can create the new volume,
1233 # then de-dup it with the existing volume
1234 $vol->label( "__SYSTEM_TMP_$$".time) if $label;
1236 $vol->creator($editor->requestor->id);
1237 $vol->create_date('now');
1238 $vol->editor($editor->requestor->id);
1239 $vol->edit_date('now');
1242 $editor->create_asset_call_number($vol) or return $editor->event;
1245 # now restore the label and merge into the existing record
1246 $vol->label($label);
1248 OpenILS::Application::Cat::Merge::merge_volumes($editor, [$vol], $$vols[0]);
1249 return $evt if $evt;
1256 __PACKAGE__->register_method (
1257 method => 'batch_volume_transfer',
1258 api_name => 'open-ils.cat.asset.volume.batch.transfer',
1261 __PACKAGE__->register_method (
1262 method => 'batch_volume_transfer',
1263 api_name => 'open-ils.cat.asset.volume.batch.transfer.override',
1267 sub batch_volume_transfer {
1268 my( $self, $conn, $auth, $args ) = @_;
1271 my $rec = $$args{docid};
1272 my $o_lib = $$args{lib};
1273 my $vol_ids = $$args{volumes};
1275 my $override = 1 if $self->api_name =~ /override/;
1277 $logger->info("merge: transferring volumes to lib=$o_lib and record=$rec");
1279 my $e = new_editor(authtoken => $auth, xact =>1);
1280 return $e->event unless $e->checkauth;
1281 return $e->event unless $e->allowed('UPDATE_VOLUME', $o_lib);
1283 my $dorg = $e->retrieve_actor_org_unit($o_lib)
1284 or return $e->event;
1286 my $ou_type = $e->retrieve_actor_org_unit_type($dorg->ou_type)
1287 or return $e->event;
1289 return $evt if ( $evt = org_cannot_have_vols($e, $o_lib) );
1291 my $vols = $e->batch_retrieve_asset_call_number($vol_ids);
1296 for my $vol (@$vols) {
1298 # if we've already looked at this volume, go to the next
1299 next if !$vol or grep { $vol->id == $_ } @seen;
1301 # grab all of the volumes in the list that have
1302 # the same label so they can be merged
1303 my @all = grep { $_->label eq $vol->label } @$vols;
1305 # take note of the fact that we've looked at this set of volumes
1306 push( @seen, $_->id ) for @all;
1307 push( @rec_ids, $_->record ) for @all;
1309 # for each volume, see if there are any copies that have a
1310 # remote circ_lib (circ_lib != vol->owning_lib and != $o_lib ).
1312 unless( $override ) {
1315 $logger->debug("merge: searching for copies with remote circ_lib for volume ".$v->id);
1317 call_number => $v->id,
1318 circ_lib => { "not in" => [ $o_lib, $v->owning_lib ] },
1322 my $copies = $e->search_asset_copy($args, {idlist=>1});
1324 # if the copy's circ_lib matches the destination lib,
1326 return OpenILS::Event->new('COPY_REMOTE_CIRC_LIB') if @$copies;
1330 # see if there is a volume at the destination lib that
1331 # already has the requested label
1332 my $existing_vol = $e->search_asset_call_number(
1334 label => $vol->label,
1336 owning_lib =>$o_lib,
1341 if( $existing_vol ) {
1343 if( grep { $_->id == $existing_vol->id } @all ) {
1344 # this volume is already accounted for in our list of volumes to merge
1345 $existing_vol = undef;
1348 # this volume exists on the destination record/owning_lib and must
1349 # be used as the destination for merging
1350 $logger->debug("merge: volume already exists at destination record: ".
1351 $existing_vol->id.' : '.$existing_vol->label) if $existing_vol;
1355 if( @all > 1 || $existing_vol ) {
1356 $logger->info("merge: found collisions in volume transfer");
1357 my @args = ($e, \@all);
1358 @args = ($e, \@all, $existing_vol) if $existing_vol;
1359 ($vol, $evt) = OpenILS::Application::Cat::Merge::merge_volumes(@args);
1360 return $evt if $evt;
1363 if( !$existing_vol ) {
1365 $vol->owning_lib($o_lib);
1367 $vol->editor($e->requestor->id);
1368 $vol->edit_date('now');
1370 $logger->info("merge: updating volume ".$vol->id);
1371 $e->update_asset_call_number($vol) or return $e->event;
1374 $logger->info("merge: bypassing volume update because existing volume used as target");
1377 # regardless of what volume was used as the destination,
1378 # update any copies that have moved over to the new lib
1379 my $copies = $e->search_asset_copy({call_number=>$vol->id, deleted => 'f'});
1381 # update circ lib on the copies - make this a method flag?
1382 for my $copy (@$copies) {
1383 next if $copy->circ_lib == $o_lib;
1384 $logger->info("merge: transfer moving circ lib on copy ".$copy->id);
1385 $copy->circ_lib($o_lib);
1386 $copy->editor($e->requestor->id);
1387 $copy->edit_date('now');
1388 $e->update_asset_copy($copy) or return $e->event;
1391 # Now see if any empty records need to be deleted after all of this
1394 $logger->debug("merge: seeing if we should delete record $_...");
1395 $evt = delete_rec($e, $_) if title_is_empty($e, $_);
1396 return $evt if $evt;
1400 # $evt = remove_empty_objects($e, $override, $_);
1404 $logger->info("merge: transfer succeeded");
1411 sub org_cannot_have_vols {
1415 my $org = $e->retrieve_actor_org_unit($org_id)
1416 or return $e->event;
1418 my $ou_type = $e->retrieve_actor_org_unit_type($org->ou_type)
1419 or return $e->event;
1421 return OpenILS::Event->new('ORG_CANNOT_HAVE_VOLS')
1422 unless $U->is_true($ou_type->can_have_vols);
1430 __PACKAGE__->register_method(
1431 api_name => 'open-ils.cat.call_number.find_or_create',
1432 method => 'find_or_create_volume',
1435 sub find_or_create_volume {
1436 my( $self, $conn, $auth, $label, $record_id, $org_id ) = @_;
1437 my $e = new_editor(authtoken=>$auth, xact=>1);
1438 return $e->die_event unless $e->checkauth;
1442 if($record_id == OILS_PRECAT_RECORD) {
1444 $vol = $e->retrieve_asset_call_number(OILS_PRECAT_CALL_NUMBER)
1445 or return $e->die_event;
1449 $vol = $e->search_asset_call_number(
1450 {label => $label, record => $record_id, owning_lib => $org_id, deleted => 'f'},
1455 # If the volume exists, return the ID
1456 if( $vol ) { $e->rollback; return $vol; }
1458 # -----------------------------------------------------------------
1459 # Otherwise, create a new volume with the given attributes
1460 # -----------------------------------------------------------------
1462 return $e->die_event unless $e->allowed('UPDATE_VOLUME', $org_id);
1464 $vol = Fieldmapper::asset::call_number->new;
1465 $vol->owning_lib($org_id);
1466 $vol->label($label);
1467 $vol->record($record_id);
1469 my $evt = create_volume( 0, $e, $vol );
1470 return $evt if $evt;