1 use strict; use warnings;
2 package OpenILS::Application::Cat;
3 use OpenILS::Application::AppUtils;
4 use OpenILS::Application;
5 use OpenILS::Application::Cat::Merge;
6 use OpenILS::Application::Cat::Authority;
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 $U = "OpenILS::Application::AppUtils";
29 __PACKAGE__->register_method(
30 method => "retrieve_marc_template",
31 api_name => "open-ils.cat.biblio.marc_template.retrieve",
33 Returns a MARC 'record tree' based on a set of pre-defined templates.
34 Templates include : book
37 sub retrieve_marc_template {
38 my( $self, $client, $type ) = @_;
39 return $marctemplates{$type} if defined($marctemplates{$type});
40 $marctemplates{$type} = _load_marc_template($type);
41 return $marctemplates{$type};
44 __PACKAGE__->register_method(
45 method => 'fetch_marc_template_types',
46 api_name => 'open-ils.cat.marc_template.types.retrieve'
49 my $marc_template_files;
51 sub fetch_marc_template_types {
52 my( $self, $conn ) = @_;
53 __load_marc_templates();
54 return [ keys %$marc_template_files ];
57 sub __load_marc_templates {
58 return if $marc_template_files;
59 if(!$conf) { $conf = OpenSRF::Utils::SettingsClient->new; }
61 $marc_template_files = $conf->config_value(
62 "apps", "open-ils.cat","app_settings", "marctemplates" );
64 $logger->info("Loaded marc templates: " . Dumper($marc_template_files));
67 sub _load_marc_template {
70 __load_marc_templates();
72 my $template = $$marc_template_files{$type};
73 open( F, $template ) or
74 throw OpenSRF::EX::ERROR ("Unable to open MARC template file: $template : $@");
78 my $xml = join('', @xml);
80 return XML::LibXML->new->parse_string($xml)->documentElement->toString;
84 sub bib_source_from_name {
86 $logger->debug("searching for bib source: $name");
90 my ($s) = grep { lc($_->source) eq lc($name) } @$__bib_sources;
97 __PACKAGE__->register_method(
98 method => 'fetch_bib_sources',
99 api_name => 'open-ils.cat.bib_sources.retrieve.all');
101 sub fetch_bib_sources {
102 $__bib_sources = new_editor()->retrieve_all_config_bib_source()
103 unless $__bib_sources;
104 return $__bib_sources;
109 __PACKAGE__->register_method(
110 method => "create_record_xml",
111 api_name => "open-ils.cat.biblio.record.xml.create.override",
112 signature => q/@see open-ils.cat.biblio.record.xml.create/);
114 __PACKAGE__->register_method(
115 method => "create_record_xml",
116 api_name => "open-ils.cat.biblio.record.xml.create",
118 Inserts a new biblio with the given XML
122 sub create_record_xml {
123 my( $self, $client, $login, $xml, $source ) = @_;
125 my $override = 1 if $self->api_name =~ /override/;
127 my( $user_obj, $evt ) = $U->checksesperm($login, 'CREATE_MARC');
130 $logger->activity("user ".$user_obj->id." creating new MARC record");
132 my $meth = $self->method_lookup("open-ils.cat.biblio.record.xml.import");
134 $meth = $self->method_lookup(
135 "open-ils.cat.biblio.record.xml.import.override") if $override;
137 my ($s) = $meth->run($login, $xml, $source);
143 __PACKAGE__->register_method(
144 method => "biblio_record_replace_marc",
145 api_name => "open-ils.cat.biblio.record.xml.update",
148 Updates the XML for a given biblio record.
149 This does not change any other aspect of the record entry
150 exception the XML, the editor, and the edit date.
151 @return The update record object
155 __PACKAGE__->register_method(
156 method => 'biblio_record_replace_marc',
157 api_name => 'open-ils.cat.biblio.record.marc.replace',
159 @param auth The authtoken
160 @param recid The record whose MARC we're replacing
161 @param newxml The new xml to use
165 __PACKAGE__->register_method(
166 method => 'biblio_record_replace_marc',
167 api_name => 'open-ils.cat.biblio.record.marc.replace.override',
168 signature => q/@see open-ils.cat.biblio.record.marc.replace/
171 sub biblio_record_replace_marc {
172 my( $self, $conn, $auth, $recid, $newxml, $source ) = @_;
174 my $e = new_editor(authtoken=>$auth, xact=>1);
175 return $e->die_event unless $e->checkauth;
176 return $e->die_event unless $e->allowed('CREATE_MARC', $e->requestor->ws_ou);
178 my $rec = $e->retrieve_biblio_record_entry($recid)
179 or return $e->die_event;
181 my $fixtcn = 1 if $self->api_name =~ /replace/o;
183 # See if there is a different record in the database that has our TCN value
184 # If we're not updating the TCN, all we care about it the marcdoc
185 my $override = $self->api_name =~ /override/;
187 # XXX should .update even bother with the tcn_info if it's not going to replace it?
188 # there is the potential for returning a TCN_EXISTS event, even though no replacement happens
190 my( $tcn, $tsource, $marcdoc, $evt);
192 if($fixtcn or $override) {
194 ($tcn, $tsource, $marcdoc, $evt) =
195 _find_tcn_info($e, $newxml, $override, $recid);
199 $rec->tcn_value($tcn) if ($tcn);
200 $rec->tcn_source($tsource);
204 $marcdoc = __make_marc_doc($newxml);
208 $rec->source(bib_source_from_name($source)) if $source;
209 $rec->editor($e->requestor->id);
210 $rec->edit_date('now');
211 $rec->marc( $U->entityize( $marcdoc->documentElement->toString ) );
212 $e->update_biblio_record_entry($rec) or return $e->die_event;
215 $conn->respond_complete($rec);
219 'open-ils.ingest.full.biblio.record', $recid );
224 __PACKAGE__->register_method(
225 method => "update_biblio_record_entry",
226 api_name => "open-ils.cat.biblio.record_entry.update",
228 Updates a biblio.record_entry
229 @param auth The authtoken
230 @param record The record with updated values
231 @return 1 on success, Event on error.
235 sub update_biblio_record_entry {
236 my($self, $conn, $auth, $record) = @_;
237 my $e = new_editor(authtoken=>$auth, xact=>1);
238 return $e->die_event unless $e->checkauth;
239 return $e->die_event unless $e->allowed('UPDATE_RECORD');
240 $e->update_biblio_record_entry($record) or return $e->die_event;
245 __PACKAGE__->register_method(
246 method => "undelete_biblio_record_entry",
247 api_name => "open-ils.cat.biblio.record_entry.undelete",
249 Un-deletes a record and sets active=true
250 @param auth The authtoken
251 @param record The record_id to ressurect
252 @return 1 on success, Event on error.
255 sub undelete_biblio_record_entry {
256 my($self, $conn, $auth, $record_id) = @_;
257 my $e = new_editor(authtoken=>$auth, xact=>1);
258 return $e->die_event unless $e->checkauth;
259 return $e->die_event unless $e->allowed('UPDATE_RECORD');
261 my $record = $e->retrieve_biblio_record_entry($record_id)
262 or return $e->die_event;
263 $record->deleted('f');
264 $record->active('t');
266 # no 2 non-deleted records can have the same tcn_value
267 my $existing = $e->search_biblio_record_entry(
269 tcn_value => $record->tcn_value,
270 id => {'!=' => $record_id}
272 return OpenILS::Event->new('TCN_EXISTS') if @$existing;
274 $e->update_biblio_record_entry($record) or return $e->die_event;
280 __PACKAGE__->register_method(
281 method => "biblio_record_xml_import",
282 api_name => "open-ils.cat.biblio.record.xml.import.override",
283 signature => q/@see open-ils.cat.biblio.record.xml.import/);
285 __PACKAGE__->register_method(
286 method => "biblio_record_xml_import",
287 api_name => "open-ils.cat.biblio.record.xml.import",
288 notes => <<" NOTES");
289 Takes a marcxml record and imports the record into the database. In this
290 case, the marcxml record is assumed to be a complete record (i.e. valid
291 MARC). The title control number is taken from (whichever comes first)
292 tags 001, 039[ab], 020a, 022a, 010, 035a and whichever does not already exist
294 user_session must have IMPORT_MARC permissions
298 sub biblio_record_xml_import {
299 my( $self, $client, $authtoken, $xml, $source, $auto_tcn) = @_;
301 my $override = 1 if $self->api_name =~ /override/;
302 my $e = new_editor(xact=>1, authtoken=>$authtoken);
303 return $e->die_event unless $e->checkauth;
304 return $e->die_event unless $e->allowed('IMPORT_MARC', $e->requestor->ws_ou);
306 my( $evt, $tcn, $tcn_source, $marcdoc );
309 # auto_tcn forces a blank TCN value so the DB will have to generate one for us
310 $marcdoc = __make_marc_doc($xml);
312 ( $tcn, $tcn_source, $marcdoc, $evt ) = _find_tcn_info($e, $xml, $override);
316 $logger->info("user ".$e->requestor->id.
317 " creating new biblio entry with tcn=$tcn and tcn_source $tcn_source");
319 my $record = Fieldmapper::biblio::record_entry->new;
321 $record->source(bib_source_from_name($source)) if $source;
322 $record->tcn_source($tcn_source);
323 $record->tcn_value($tcn) if ($tcn);
324 $record->creator($e->requestor->id);
325 $record->editor($e->requestor->id);
326 $record->create_date('now');
327 $record->edit_date('now');
328 $record->marc( $U->entityize( $marcdoc->documentElement->toString ) );
330 $record = $e->create_biblio_record_entry($record) or return $e->die_event;
331 $logger->info("marc create/import created new record ".$record->id);
335 $logger->debug("Sending record off to be ingested and indexed");
337 $client->respond_complete($record);
341 'open-ils.ingest.full.biblio.record', $record->id );
346 sub __make_marc_doc {
348 my $marcxml = XML::LibXML->new->parse_string( $xml );
349 $marcxml->documentElement->setNamespace(
350 "http://www.loc.gov/MARC21/slim", "marc", 1 );
351 $marcxml->documentElement->setNamespace("http://www.loc.gov/MARC21/slim");
359 my $override = shift;
360 my $existing_rec = shift || 0;
363 my $marcxml = __make_marc_doc($xml);
365 my $xpath = '//marc:controlfield[@tag="001"]';
366 my $tcn = $marcxml->documentElement->findvalue($xpath);
367 $logger->info("biblio import located 001 (tcn) value of $tcn");
369 $xpath = '//marc:controlfield[@tag="003"]';
370 my $tcn_source = $marcxml->documentElement->findvalue($xpath) || "System Local";
372 if(my $rec = _tcn_exists($editor, $tcn, $tcn_source, $existing_rec) ) {
375 $tcn = find_free_tcn( $marcxml, $editor, $existing_rec );
377 # if we're overriding, try to find a different TCN to use
380 # XXX Create ALLOW_ALT_TCN permission check support
382 $logger->info("tcn value $tcn already exists, attempting to override");
390 'OPEN_TCN_NOT_FOUND',
391 payload => $marcxml->toString())
397 $logger->warn("tcn value $origtcn already exists in import/create");
399 # otherwise, return event
405 'TCN_EXISTS', payload => {
415 return ($tcn, $tcn_source, $marcxml);
422 my $existing_rec = shift;
426 my $xpath = '//marc:datafield[@tag="039"]/subfield[@code="a"]';
427 my ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
428 $xpath = '//marc:datafield[@tag="039"]/subfield[@code="b"]';
429 my $tcn_source = $marcxml->documentElement->findvalue($xpath) || "System Local";
431 if(_tcn_exists($editor, $tcn, $tcn_source, $existing_rec)) {
439 $xpath = '//marc:datafield[@tag="020"]/subfield[@code="a"]';
440 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
441 $tcn_source = "ISBN";
442 if(_tcn_exists($editor, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
446 $xpath = '//marc:datafield[@tag="022"]/subfield[@code="a"]';
447 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
448 $tcn_source = "ISSN";
449 if(_tcn_exists($editor, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
453 $xpath = '//marc:datafield[@tag="010"]';
454 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
455 $tcn_source = "LCCN";
456 if(_tcn_exists($editor, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
460 $xpath = '//marc:datafield[@tag="035"]/subfield[@code="a"]';
461 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
462 $tcn_source = "System Legacy";
463 if(_tcn_exists($editor, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
466 $marcxml->documentElement->removeChild(
467 $marcxml->documentElement->findnodes( '//datafield[@tag="035"]' )
472 return undef unless $tcn;
475 my $df = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'datafield');
476 $df->setAttribute( tag => '039' );
477 $df->setAttribute( ind1 => ' ' );
478 $df->setAttribute( ind2 => ' ' );
479 $marcxml->documentElement->appendChild( $df );
481 my $sfa = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'subfield');
482 $sfa->setAttribute( code => 'a' );
483 $sfa->appendChild( $marcxml->createTextNode( $tcn ) );
484 $df->appendChild( $sfa );
486 my $sfb = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'subfield');
487 $sfb->setAttribute( code => 'b' );
488 $sfb->appendChild( $marcxml->createTextNode( $tcn_source ) );
489 $df->appendChild( $sfb );
501 my $existing_rec = shift || 0;
503 if(!$tcn) {return 0;}
505 $logger->debug("tcn_exists search for tcn $tcn and source $source and id $existing_rec");
507 # XXX why does the source matter?
508 # my $req = $session->request(
509 # { tcn_value => $tcn, tcn_source => $source, deleted => 'f' } );
511 my $recs = $editor->search_biblio_record_entry(
512 {tcn_value => $tcn, deleted => 'f', id => {'!=' => $existing_rec}}, {idlist =>1});
515 $logger->debug("_tcn_exists is true for tcn : $tcn ($source)");
519 $logger->debug("_tcn_exists is false for tcn : $tcn ($source)");
524 __PACKAGE__->register_method(
525 method => "biblio_record_record_metadata",
526 api_name => "open-ils.cat.biblio.record.metadata.retrieve",
528 argc => 1, #(session_id, biblio_tree )
529 notes => "Walks the tree and commits any changed nodes " .
530 "adds any new nodes, and deletes any deleted nodes",
533 sub biblio_record_record_metadata {
534 my( $self, $client, $authtoken, $ids ) = @_;
536 return [] unless $ids and @$ids;
538 my $editor = new_editor(authtoken => $authtoken);
539 return $editor->event unless $editor->checkauth;
540 return $editor->event unless $editor->allowed('VIEW_USER');
545 return $editor->event unless
546 my $rec = $editor->retrieve_biblio_record_entry($_);
547 $rec->creator($editor->retrieve_actor_user($rec->creator));
548 $rec->editor($editor->retrieve_actor_user($rec->editor));
549 $rec->clear_marc; # slim the record down
550 push( @results, $rec );
558 __PACKAGE__->register_method(
559 method => "biblio_record_marc_cn",
560 api_name => "open-ils.cat.biblio.record.marc_cn.retrieve",
561 argc => 1, #(bib id )
564 sub biblio_record_marc_cn {
565 my( $self, $client, $id ) = @_;
567 my $session = OpenSRF::AppSession->create("open-ils.cstore");
569 ->request("open-ils.cstore.direct.biblio.record_entry.retrieve", $id )
573 my $doc = XML::LibXML->new->parse_string($marc);
574 $doc->documentElement->setNamespace( "http://www.loc.gov/MARC21/slim", "marc", 1 );
577 for my $tag ( qw/050 055 060 070 080 082 086 088 090 092 096 098 099/ ) {
578 my @node = $doc->findnodes("//marc:datafield[\@tag='$tag']");
580 my $cn = $x->findvalue("marc:subfield[\@code='a' or \@code='b']");
581 push @res, {$tag => $cn} if ($cn);
588 sub _get_id_by_userid {
593 my $session = OpenSRF::AppSession->create( "open-ils.cstore" );
594 my $request = $session->request(
595 "open-ils.cstore.direct.actor.user.search.atomic", { usrname => \@users } );
597 $request->wait_complete;
598 my $response = $request->recv();
599 if(!$request->complete) {
600 throw OpenSRF::EX::ERROR ("no response from cstore on user retrieve");
603 if(UNIVERSAL::isa( $response, "Error")){
604 throw $response ($response);
607 for my $u (@{$response->content}) {
613 $session->disconnect;
620 # commits metadata objects to the db
621 sub _update_record_metadata {
623 my ($session, @docs ) = @_;
625 for my $doc (@docs) {
627 my $user_obj = $doc->{user};
628 my $docid = $doc->{docid};
630 my $request = $session->request(
631 "open-ils.storage.direct.biblio.record_entry.retrieve", $docid );
632 my $record = $request->gather(1);
634 my ($id) = _get_id_by_userid($user_obj->usrname);
636 $record->editor($id);
638 $request = $session->request(
639 "open-ils.storage.direct.biblio.record_entry.update", $record );
648 __PACKAGE__->register_method(
649 method => "orgs_for_title",
651 api_name => "open-ils.cat.actor.org_unit.retrieve_by_title"
655 my( $self, $client, $record_id ) = @_;
657 my $vols = $U->simple_scalar_request(
659 "open-ils.cstore.direct.asset.call_number.search.atomic",
660 { record => $record_id, deleted => 'f' });
662 my $orgs = { map {$_->owning_lib => 1 } @$vols };
663 return [ keys %$orgs ];
667 __PACKAGE__->register_method(
668 method => "retrieve_copies",
670 api_name => "open-ils.cat.asset.copy_tree.retrieve");
672 __PACKAGE__->register_method(
673 method => "retrieve_copies",
674 api_name => "open-ils.cat.asset.copy_tree.global.retrieve");
676 # user_session may be null/undef
677 sub retrieve_copies {
679 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
681 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
685 # grabbing copy trees should be available for everyone..
686 if(!@org_ids and $user_session) {
688 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
689 @org_ids = ($user_obj->home_ou);
692 if( $self->api_name =~ /global/ ) {
693 return _build_volume_list( { record => $docid, deleted => 'f' } );
698 for my $orgid (@org_ids) {
699 my $vols = _build_volume_list(
700 { record => $docid, owning_lib => $orgid, deleted => 'f' } );
701 push( @all_vols, @$vols );
711 sub _build_volume_list {
712 my $search_hash = shift;
714 $search_hash->{deleted} = 'f';
715 my $e = new_editor();
717 my $vols = $e->search_asset_call_number($search_hash);
721 for my $volume (@$vols) {
723 my $copies = $e->search_asset_copy(
724 { call_number => $volume->id , deleted => 'f' });
726 $copies = [ sort { $a->barcode cmp $b->barcode } @$copies ];
728 for my $c (@$copies) {
729 if( $c->status == OILS_COPY_STATUS_CHECKED_OUT ) {
731 $e->search_action_circulation(
733 { target_copy => $c->id },
735 order_by => { circ => 'xact_start desc' },
744 $volume->copies($copies);
745 push( @volumes, $volume );
748 #$session->disconnect();
754 __PACKAGE__->register_method(
755 method => "fleshed_copy_update",
756 api_name => "open-ils.cat.asset.copy.fleshed.batch.update",);
758 __PACKAGE__->register_method(
759 method => "fleshed_copy_update",
760 api_name => "open-ils.cat.asset.copy.fleshed.batch.update.override",);
763 sub fleshed_copy_update {
764 my( $self, $conn, $auth, $copies, $delete_stats ) = @_;
765 return 1 unless ref $copies;
766 my( $reqr, $evt ) = $U->checkses($auth);
768 my $editor = new_editor(requestor => $reqr, xact => 1);
769 my $override = $self->api_name =~ /override/;
770 $evt = update_fleshed_copies($editor, $override, undef, $copies, $delete_stats);
772 $logger->info("fleshed copy update failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
777 $logger->info("fleshed copy update successfully updated ".scalar(@$copies)." copies");
782 __PACKAGE__->register_method(
784 api_name => 'open-ils.cat.biblio.records.merge',
786 Merges a group of records
787 @param auth The login session key
788 @param master The id of the record all other records should be merged into
789 @param records Array of records to be merged into the master record
790 @return 1 on success, Event on error.
795 my( $self, $conn, $auth, $master, $records ) = @_;
796 my( $reqr, $evt ) = $U->checkses($auth);
798 my $editor = new_editor( requestor => $reqr, xact => 1 );
799 my $v = OpenILS::Application::Cat::Merge::merge_records($editor, $master, $records);
802 # tell the client the merge is complete, then merge the holds
803 $conn->respond_complete(1);
804 merge_holds($master, $records);
809 my($master, $records) = @_;
810 return unless $master and @$records;
811 return if @$records == 1 and $master == $$records[0];
813 my $e = new_editor(xact=>1);
814 my $holds = $e->search_action_hold_request(
815 { cancel_time => undef,
816 fulfillment_time => undef,
823 for my $hold_id (@$holds) {
825 my $hold = $e->retrieve_action_hold_request($hold_id);
827 $logger->info("Changing hold ".$hold->id.
828 " target from ".$hold->target." to $master in record merge");
830 $hold->target($master);
831 unless($e->update_action_hold_request($hold)) {
833 $logger->error("Error updating hold ". $evt->textcode .":". $evt->desc .":". $evt->stacktrace);
844 # ---------------------------------------------------------------------------
845 # returns true if the given title (id) has no un-deleted volumes or
846 # copies attached. If a context volume is defined, a record
847 # is considered empty only if the context volume is the only
848 # remaining volume on the record.
849 # ---------------------------------------------------------------------------
851 my( $editor, $rid, $vol_id ) = @_;
853 return 0 if $rid == OILS_PRECAT_RECORD;
855 my $cnlist = $editor->search_asset_call_number(
856 { record => $rid, deleted => 'f' }, { idlist => 1 } );
858 return 1 unless @$cnlist; # no attached volumes
859 return 0 if @$cnlist > 1; # multiple attached volumes
860 return 0 unless $$cnlist[0] == $vol_id; # attached volume is not the context vol.
862 # see if the sole remaining context volume has any attached copies
863 for my $cn (@$cnlist) {
864 my $copylist = $editor->search_asset_copy(
866 { call_number => $cn, deleted => 'f' },
869 return 0 if @$copylist; # false if we find any copies
876 __PACKAGE__->register_method(
877 method => "fleshed_volume_update",
878 api_name => "open-ils.cat.asset.volume.fleshed.batch.update",);
880 __PACKAGE__->register_method(
881 method => "fleshed_volume_update",
882 api_name => "open-ils.cat.asset.volume.fleshed.batch.update.override",);
884 sub fleshed_volume_update {
885 my( $self, $conn, $auth, $volumes, $delete_stats ) = @_;
886 my( $reqr, $evt ) = $U->checkses($auth);
889 my $override = ($self->api_name =~ /override/);
890 my $editor = new_editor( requestor => $reqr, xact => 1 );
892 for my $vol (@$volumes) {
893 $logger->info("vol-update: investigating volume ".$vol->id);
895 $vol->editor($reqr->id);
896 $vol->edit_date('now');
898 my $copies = $vol->copies;
901 $vol->editor($editor->requestor->id);
902 $vol->edit_date('now');
904 if( $vol->isdeleted ) {
906 $logger->info("vol-update: deleting volume");
907 my $cs = $editor->search_asset_copy(
908 { call_number => $vol->id, deleted => 'f' } );
909 return OpenILS::Event->new(
910 'VOLUME_NOT_EMPTY', payload => $vol->id ) if @$cs;
913 return $editor->event unless
914 $editor->update_asset_call_number($vol);
917 } elsif( $vol->isnew ) {
918 $logger->info("vol-update: creating volume");
919 $evt = create_volume( $override, $editor, $vol );
922 } elsif( $vol->ischanged ) {
923 $logger->info("vol-update: update volume");
924 $evt = update_volume($vol, $editor);
928 # now update any attached copies
929 if( $copies and @$copies and !$vol->isdeleted ) {
930 $_->call_number($vol->id) for @$copies;
931 $evt = update_fleshed_copies( $editor, $override, $vol, $copies, $delete_stats );
937 return scalar(@$volumes);
946 return $evt if ( $evt = org_cannot_have_vols($editor, $vol->owning_lib) );
948 my $vols = $editor->search_asset_call_number( {
949 owning_lib => $vol->owning_lib,
950 record => $vol->record,
951 label => $vol->label,
956 # There exists a different volume in the DB with the same properties
957 return OpenILS::Event->new('VOLUME_LABEL_EXISTS', payload => $vol->id)
958 if grep { $_->id ne $vol->id } @$vols;
960 return $editor->event unless $editor->update_asset_call_number($vol);
967 my( $vol, $copy ) = @_;
968 my $org = $vol->owning_lib;
969 if( $vol->id == OILS_PRECAT_CALL_NUMBER ) {
970 $org = ref($copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
972 $logger->debug("using copy perm org $org");
977 # this does the actual work
978 sub update_fleshed_copies {
979 my( $editor, $override, $vol, $copies, $delete_stats ) = @_;
982 my $fetchvol = ($vol) ? 0 : 1;
985 $cache{$vol->id} = $vol if $vol;
987 for my $copy (@$copies) {
989 my $copyid = $copy->id;
990 $logger->info("vol-update: inspecting copy $copyid");
992 if( !($vol = $cache{$copy->call_number}) ) {
993 $vol = $cache{$copy->call_number} =
994 $editor->retrieve_asset_call_number($copy->call_number);
995 return $editor->event unless $vol;
998 return $editor->event unless
999 $editor->allowed('UPDATE_COPY', copy_perm_org($vol, $copy));
1001 $copy->editor($editor->requestor->id);
1002 $copy->edit_date('now');
1004 $copy->status( $copy->status->id ) if ref($copy->status);
1005 $copy->location( $copy->location->id ) if ref($copy->location);
1006 $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
1008 my $sc_entries = $copy->stat_cat_entries;
1009 $copy->clear_stat_cat_entries;
1011 if( $copy->isdeleted ) {
1012 $evt = delete_copy($editor, $override, $vol, $copy);
1013 return $evt if $evt;
1015 } elsif( $copy->isnew ) {
1016 $evt = create_copy( $editor, $vol, $copy );
1017 return $evt if $evt;
1019 } elsif( $copy->ischanged ) {
1021 $evt = update_copy( $editor, $override, $vol, $copy );
1022 return $evt if $evt;
1025 $copy->stat_cat_entries( $sc_entries );
1026 $evt = update_copy_stat_entries($editor, $copy, $delete_stats);
1027 return $evt if $evt;
1030 $logger->debug("vol-update: done updating copy batch");
1035 sub fix_copy_price {
1038 if(defined $copy->price) {
1039 my $p = $copy->price || 0;
1044 my $d = $copy->deposit_amount || 0;
1046 $copy->deposit_amount($d);
1051 my( $editor, $override, $vol, $copy ) = @_;
1054 my $org = (ref $copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
1055 return $evt if ( $evt = org_cannot_have_vols($editor, $org) );
1057 $logger->info("vol-update: updating copy ".$copy->id);
1058 my $orig_copy = $editor->retrieve_asset_copy($copy->id);
1059 my $orig_vol = $editor->retrieve_asset_call_number($copy->call_number);
1061 $copy->editor($editor->requestor->id);
1062 $copy->edit_date('now');
1064 $copy->age_protect( $copy->age_protect->id )
1065 if ref $copy->age_protect;
1067 fix_copy_price($copy);
1069 return $editor->event unless $editor->update_asset_copy($copy);
1070 return remove_empty_objects($editor, $override, $orig_vol);
1074 sub remove_empty_objects {
1075 my( $editor, $override, $vol ) = @_;
1077 my $koe = $U->ou_ancestor_setting_value(
1078 $editor->requestor->ws_ou, 'cat.bib.keep_on_empty', $editor);
1079 my $aoe = $U->ou_ancestor_setting_value(
1080 $editor->requestor->ws_ou, 'cat.bib.alert_on_empty', $editor);
1082 if( title_is_empty($editor, $vol->record, $vol->id) ) {
1084 # delete this volume if it's not already marked as deleted
1085 unless( $U->is_true($vol->deleted) || $vol->isdeleted ) {
1087 $vol->editor($editor->requestor->id);
1088 $vol->edit_date('now');
1089 $editor->update_asset_call_number($vol) or return $editor->event;
1093 # delete the bib record if the keep-on-empty setting is not set
1094 my $evt = delete_rec($editor, $vol->record);
1095 return $evt if $evt;
1098 # return the empty alert if the alert-on-empty setting is set
1099 return OpenILS::Event->new('TITLE_LAST_COPY', payload => $vol->record ) if $aoe;
1106 __PACKAGE__->register_method (
1107 method => 'delete_bib_record',
1108 api_name => 'open-ils.cat.biblio.record_entry.delete');
1110 sub delete_bib_record {
1111 my($self, $conn, $auth, $rec_id) = @_;
1112 my $e = new_editor(xact=>1, authtoken=>$auth);
1113 return $e->die_event unless $e->checkauth;
1114 return $e->die_event unless $e->allowed('DELETE_RECORD', $e->requestor->ws_ou);
1115 my $vols = $e->search_asset_call_number({record=>$rec_id, deleted=>'f'});
1116 return OpenILS::Event->new('RECORD_NOT_EMPTY', payload=>$rec_id) if @$vols;
1117 my $evt = delete_rec($e, $rec_id);
1118 if($evt) { $e->rollback; return $evt; }
1124 # marks a record as deleted
1126 my( $editor, $rec_id ) = @_;
1128 my $rec = $editor->retrieve_biblio_record_entry($rec_id)
1129 or return $editor->event;
1131 return undef if $U->is_true($rec->deleted);
1135 $rec->editor( $editor->requestor->id );
1136 $rec->edit_date('now');
1137 $editor->update_biblio_record_entry($rec) or return $editor->event;
1144 my( $editor, $override, $vol, $copy ) = @_;
1146 return $editor->event unless
1147 $editor->allowed('DELETE_COPY',copy_perm_org($vol, $copy));
1149 my $stat = $U->copy_status($copy->status)->id;
1152 return OpenILS::Event->new('COPY_DELETE_WARNING', payload => $copy->id )
1153 if $stat == OILS_COPY_STATUS_CHECKED_OUT or
1154 $stat == OILS_COPY_STATUS_IN_TRANSIT or
1155 $stat == OILS_COPY_STATUS_ON_HOLDS_SHELF or
1156 $stat == OILS_COPY_STATUS_ILL;
1159 $logger->info("vol-update: deleting copy ".$copy->id);
1160 $copy->deleted('t');
1162 $copy->editor($editor->requestor->id);
1163 $copy->edit_date('now');
1164 $editor->update_asset_copy($copy) or return $editor->event;
1166 # Delete any open transits for this copy
1167 my $transits = $editor->search_action_transit_copy(
1168 { target_copy=>$copy->id, dest_recv_time => undef } );
1170 for my $t (@$transits) {
1171 $editor->delete_action_transit_copy($t)
1172 or return $editor->event;
1175 return remove_empty_objects($editor, $override, $vol);
1180 my( $editor, $vol, $copy ) = @_;
1182 my $existing = $editor->search_asset_copy(
1183 { barcode => $copy->barcode, deleted => 'f' } );
1185 return OpenILS::Event->new('ITEM_BARCODE_EXISTS') if @$existing;
1187 # see if the volume this copy references is marked as deleted
1188 my $evol = $editor->retrieve_asset_call_number($copy->call_number)
1189 or return $editor->event;
1190 return OpenILS::Event->new('VOLUME_DELETED', vol => $evol->id)
1191 if $U->is_true($evol->deleted);
1194 my $org = (ref $copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
1195 return $evt if ( $evt = org_cannot_have_vols($editor, $org) );
1198 $copy->creator($editor->requestor->id);
1199 $copy->create_date('now');
1200 fix_copy_price($copy);
1202 $editor->create_asset_copy($copy) or return $editor->event;
1206 # if 'delete_stats' is true, the copy->stat_cat_entries data is
1207 # treated as the authoritative list for the copy. existing entries
1208 # that are not in said list will be deleted from the DB
1209 sub update_copy_stat_entries {
1210 my( $editor, $copy, $delete_stats ) = @_;
1212 return undef if $copy->isdeleted;
1213 return undef unless $copy->ischanged or $copy->isnew;
1216 my $entries = $copy->stat_cat_entries;
1218 if( $delete_stats ) {
1219 $entries = ($entries and @$entries) ? $entries : [];
1221 return undef unless ($entries and @$entries);
1224 my $maps = $editor->search_asset_stat_cat_entry_copy_map({owning_copy=>$copy->id});
1227 # if there is no stat cat entry on the copy who's id matches the
1228 # current map's id, remove the map from the database
1229 for my $map (@$maps) {
1230 if(! grep { $_->id == $map->stat_cat_entry } @$entries ) {
1232 $logger->info("copy update found stale ".
1233 "stat cat entry map ".$map->id. " on copy ".$copy->id);
1235 $editor->delete_asset_stat_cat_entry_copy_map($map)
1236 or return $editor->event;
1241 # go through the stat cat update/create process
1242 for my $entry (@$entries) {
1245 # if this link already exists in the DB, don't attempt to re-create it
1246 next if( grep{$_->stat_cat_entry == $entry->id} @$maps );
1248 my $new_map = Fieldmapper::asset::stat_cat_entry_copy_map->new();
1250 my $sc = ref($entry->stat_cat) ? $entry->stat_cat->id : $entry->stat_cat;
1252 $new_map->stat_cat( $sc );
1253 $new_map->stat_cat_entry( $entry->id );
1254 $new_map->owning_copy( $copy->id );
1256 $editor->create_asset_stat_cat_entry_copy_map($new_map)
1257 or return $editor->event;
1259 $logger->info("copy update created new stat cat entry map ".$editor->data);
1267 my( $override, $editor, $vol ) = @_;
1270 return $evt if ( $evt = org_cannot_have_vols($editor, $vol->owning_lib) );
1272 # see if the record this volume references is marked as deleted
1273 my $rec = $editor->retrieve_biblio_record_entry($vol->record)
1274 or return $editor->event;
1275 return OpenILS::Event->new('BIB_RECORD_DELETED', rec => $rec->id)
1276 if $U->is_true($rec->deleted);
1278 # first lets see if there are any collisions
1279 my $vols = $editor->search_asset_call_number( {
1280 owning_lib => $vol->owning_lib,
1281 record => $vol->record,
1282 label => $vol->label,
1289 # we've found an exising volume
1291 $label = $vol->label;
1293 return OpenILS::Event->new(
1294 'VOLUME_LABEL_EXISTS', payload => $vol->id);
1298 # create a temp label so we can create the new volume,
1299 # then de-dup it with the existing volume
1300 $vol->label( "__SYSTEM_TMP_$$".time) if $label;
1302 $vol->creator($editor->requestor->id);
1303 $vol->create_date('now');
1304 $vol->editor($editor->requestor->id);
1305 $vol->edit_date('now');
1308 $editor->create_asset_call_number($vol) or return $editor->event;
1311 # now restore the label and merge into the existing record
1312 $vol->label($label);
1314 OpenILS::Application::Cat::Merge::merge_volumes($editor, [$vol], $$vols[0]);
1315 return $evt if $evt;
1322 __PACKAGE__->register_method (
1323 method => 'batch_volume_transfer',
1324 api_name => 'open-ils.cat.asset.volume.batch.transfer',
1327 __PACKAGE__->register_method (
1328 method => 'batch_volume_transfer',
1329 api_name => 'open-ils.cat.asset.volume.batch.transfer.override',
1333 sub batch_volume_transfer {
1334 my( $self, $conn, $auth, $args ) = @_;
1337 my $rec = $$args{docid};
1338 my $o_lib = $$args{lib};
1339 my $vol_ids = $$args{volumes};
1341 my $override = 1 if $self->api_name =~ /override/;
1343 $logger->info("merge: transferring volumes to lib=$o_lib and record=$rec");
1345 my $e = new_editor(authtoken => $auth, xact =>1);
1346 return $e->event unless $e->checkauth;
1347 return $e->event unless $e->allowed('UPDATE_VOLUME', $o_lib);
1349 my $dorg = $e->retrieve_actor_org_unit($o_lib)
1350 or return $e->event;
1352 my $ou_type = $e->retrieve_actor_org_unit_type($dorg->ou_type)
1353 or return $e->event;
1355 return $evt if ( $evt = org_cannot_have_vols($e, $o_lib) );
1357 my $vols = $e->batch_retrieve_asset_call_number($vol_ids);
1362 for my $vol (@$vols) {
1364 # if we've already looked at this volume, go to the next
1365 next if !$vol or grep { $vol->id == $_ } @seen;
1367 # grab all of the volumes in the list that have
1368 # the same label so they can be merged
1369 my @all = grep { $_->label eq $vol->label } @$vols;
1371 # take note of the fact that we've looked at this set of volumes
1372 push( @seen, $_->id ) for @all;
1373 push( @rec_ids, $_->record ) for @all;
1375 # for each volume, see if there are any copies that have a
1376 # remote circ_lib (circ_lib != vol->owning_lib and != $o_lib ).
1378 unless( $override ) {
1381 $logger->debug("merge: searching for copies with remote circ_lib for volume ".$v->id);
1383 call_number => $v->id,
1384 circ_lib => { "not in" => [ $o_lib, $v->owning_lib ] },
1388 my $copies = $e->search_asset_copy($args, {idlist=>1});
1390 # if the copy's circ_lib matches the destination lib,
1392 return OpenILS::Event->new('COPY_REMOTE_CIRC_LIB') if @$copies;
1396 # see if there is a volume at the destination lib that
1397 # already has the requested label
1398 my $existing_vol = $e->search_asset_call_number(
1400 label => $vol->label,
1402 owning_lib =>$o_lib,
1407 if( $existing_vol ) {
1409 if( grep { $_->id == $existing_vol->id } @all ) {
1410 # this volume is already accounted for in our list of volumes to merge
1411 $existing_vol = undef;
1414 # this volume exists on the destination record/owning_lib and must
1415 # be used as the destination for merging
1416 $logger->debug("merge: volume already exists at destination record: ".
1417 $existing_vol->id.' : '.$existing_vol->label) if $existing_vol;
1421 if( @all > 1 || $existing_vol ) {
1422 $logger->info("merge: found collisions in volume transfer");
1423 my @args = ($e, \@all);
1424 @args = ($e, \@all, $existing_vol) if $existing_vol;
1425 ($vol, $evt) = OpenILS::Application::Cat::Merge::merge_volumes(@args);
1426 return $evt if $evt;
1429 if( !$existing_vol ) {
1431 $vol->owning_lib($o_lib);
1433 $vol->editor($e->requestor->id);
1434 $vol->edit_date('now');
1436 $logger->info("merge: updating volume ".$vol->id);
1437 $e->update_asset_call_number($vol) or return $e->event;
1440 $logger->info("merge: bypassing volume update because existing volume used as target");
1443 # regardless of what volume was used as the destination,
1444 # update any copies that have moved over to the new lib
1445 my $copies = $e->search_asset_copy({call_number=>$vol->id, deleted => 'f'});
1447 # update circ lib on the copies - make this a method flag?
1448 for my $copy (@$copies) {
1449 next if $copy->circ_lib == $o_lib;
1450 $logger->info("merge: transfer moving circ lib on copy ".$copy->id);
1451 $copy->circ_lib($o_lib);
1452 $copy->editor($e->requestor->id);
1453 $copy->edit_date('now');
1454 $e->update_asset_copy($copy) or return $e->event;
1457 # Now see if any empty records need to be deleted after all of this
1460 $logger->debug("merge: seeing if we should delete record $_...");
1461 $evt = delete_rec($e, $_) if title_is_empty($e, $_);
1462 return $evt if $evt;
1466 # $evt = remove_empty_objects($e, $override, $_);
1470 $logger->info("merge: transfer succeeded");
1477 sub org_cannot_have_vols {
1481 my $org = $e->retrieve_actor_org_unit($org_id)
1482 or return $e->event;
1484 my $ou_type = $e->retrieve_actor_org_unit_type($org->ou_type)
1485 or return $e->event;
1487 return OpenILS::Event->new('ORG_CANNOT_HAVE_VOLS')
1488 unless $U->is_true($ou_type->can_have_vols);
1496 __PACKAGE__->register_method(
1497 api_name => 'open-ils.cat.call_number.find_or_create',
1498 method => 'find_or_create_volume',
1501 sub find_or_create_volume {
1502 my( $self, $conn, $auth, $label, $record_id, $org_id ) = @_;
1503 my $e = new_editor(authtoken=>$auth, xact=>1);
1504 return $e->die_event unless $e->checkauth;
1508 if($record_id == OILS_PRECAT_RECORD) {
1510 $vol = $e->retrieve_asset_call_number(OILS_PRECAT_CALL_NUMBER)
1511 or return $e->die_event;
1515 $vol = $e->search_asset_call_number(
1516 {label => $label, record => $record_id, owning_lib => $org_id, deleted => 'f'},
1521 # If the volume exists, return the ID
1522 if( $vol ) { $e->rollback; return $vol; }
1524 # -----------------------------------------------------------------
1525 # Otherwise, create a new volume with the given attributes
1526 # -----------------------------------------------------------------
1528 return $e->die_event unless $e->allowed('UPDATE_VOLUME', $org_id);
1530 $vol = Fieldmapper::asset::call_number->new;
1531 $vol->owning_lib($org_id);
1532 $vol->label($label);
1533 $vol->record($record_id);
1535 my $evt = create_volume( 0, $e, $vol );
1536 return $evt if $evt;