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 my $e = new_editor(authtoken=>$auth, xact=>1);
194 return $e->die_event unless $e->checkauth;
195 return $e->die_event unless $e->allowed('CREATE_MARC', $e->requestor->ws_ou);
197 my $rec = $e->retrieve_biblio_record_entry($recid)
198 or return $e->die_event;
200 my $fixtcn = 1 if $self->api_name =~ /replace/o;
202 # See if there is a different record in the database that has our TCN value
203 # If we're not updating the TCN, all we care about it the marcdoc
204 my $override = $self->api_name =~ /override/;
206 # XXX should .update even bother with the tcn_info if it's not going to replace it?
207 # there is the potential for returning a TCN_EXISTS event, even though no replacement happens
209 my( $tcn, $tsource, $marcdoc, $evt);
211 if($fixtcn or $override) {
213 ($tcn, $tsource, $marcdoc, $evt) =
214 _find_tcn_info($e, $newxml, $override, $recid);
218 $rec->tcn_value($tcn) if ($tcn);
219 $rec->tcn_source($tsource);
223 $marcdoc = __make_marc_doc($newxml);
227 $rec->source(bib_source_from_name($source)) if $source;
228 $rec->editor($e->requestor->id);
229 $rec->edit_date('now');
230 $rec->marc( entityize( $marcdoc->documentElement->toString ) );
231 $e->update_biblio_record_entry($rec) or return $e->die_event;
234 $conn->respond_complete($rec);
238 'open-ils.ingest.full.biblio.record', $recid );
243 __PACKAGE__->register_method(
244 method => "update_biblio_record_entry",
245 api_name => "open-ils.cat.biblio.record_entry.update",
247 Updates a biblio.record_entry
248 @param auth The authtoken
249 @param record The record with updated values
250 @return 1 on success, Event on error.
254 sub update_biblio_record_entry {
255 my($self, $conn, $auth, $record) = @_;
256 my $e = new_editor(authtoken=>$auth, xact=>1);
257 return $e->die_event unless $e->checkauth;
258 return $e->die_event unless $e->allowed('UPDATE_RECORD');
259 $e->update_biblio_record_entry($record) or return $e->die_event;
264 __PACKAGE__->register_method(
265 method => "undelete_biblio_record_entry",
266 api_name => "open-ils.cat.biblio.record_entry.undelete",
268 Un-deletes a record and sets active=true
269 @param auth The authtoken
270 @param record The record_id to ressurect
271 @return 1 on success, Event on error.
274 sub undelete_biblio_record_entry {
275 my($self, $conn, $auth, $record_id) = @_;
276 my $e = new_editor(authtoken=>$auth, xact=>1);
277 return $e->die_event unless $e->checkauth;
278 return $e->die_event unless $e->allowed('UPDATE_RECORD');
280 my $record = $e->retrieve_biblio_record_entry($record_id)
281 or return $e->die_event;
282 $record->deleted('f');
283 $record->active('t');
285 # no 2 non-deleted records can have the same tcn_value
286 my $existing = $e->search_biblio_record_entry(
288 tcn_value => $record->tcn_value,
289 id => {'!=' => $record_id}
291 return OpenILS::Event->new('TCN_EXISTS') if @$existing;
293 $e->update_biblio_record_entry($record) or return $e->die_event;
299 __PACKAGE__->register_method(
300 method => "biblio_record_xml_import",
301 api_name => "open-ils.cat.biblio.record.xml.import.override",
302 signature => q/@see open-ils.cat.biblio.record.xml.import/);
304 __PACKAGE__->register_method(
305 method => "biblio_record_xml_import",
306 api_name => "open-ils.cat.biblio.record.xml.import",
307 notes => <<" NOTES");
308 Takes a marcxml record and imports the record into the database. In this
309 case, the marcxml record is assumed to be a complete record (i.e. valid
310 MARC). The title control number is taken from (whichever comes first)
311 tags 001, 039[ab], 020a, 022a, 010, 035a and whichever does not already exist
313 user_session must have IMPORT_MARC permissions
317 sub biblio_record_xml_import {
318 my( $self, $client, $authtoken, $xml, $source, $auto_tcn) = @_;
320 my $override = 1 if $self->api_name =~ /override/;
321 my $e = new_editor(xact=>1, authtoken=>$authtoken);
322 return $e->die_event unless $e->checkauth;
323 return $e->die_event unless $e->allowed('IMPORT_MARC', $e->requestor->ws_ou);
325 my( $evt, $tcn, $tcn_source, $marcdoc );
328 # auto_tcn forces a blank TCN value so the DB will have to generate one for us
329 $marcdoc = __make_marc_doc($xml);
331 ( $tcn, $tcn_source, $marcdoc, $evt ) = _find_tcn_info($e, $xml, $override);
335 $logger->info("user ".$e->requestor->id.
336 " creating new biblio entry with tcn=$tcn and tcn_source $tcn_source");
338 my $record = Fieldmapper::biblio::record_entry->new;
340 $record->source(bib_source_from_name($source)) if $source;
341 $record->tcn_source($tcn_source);
342 $record->tcn_value($tcn) if ($tcn);
343 $record->creator($e->requestor->id);
344 $record->editor($e->requestor->id);
345 $record->create_date('now');
346 $record->edit_date('now');
347 $record->marc( entityize( $marcdoc->documentElement->toString ) );
349 $record = $e->create_biblio_record_entry($record) or return $e->die_event;
350 $logger->info("marc create/import created new record ".$record->id);
354 $logger->debug("Sending record off to be ingested and indexed");
356 $client->respond_complete($record);
360 'open-ils.ingest.full.biblio.record', $record->id );
365 sub __make_marc_doc {
367 my $marcxml = XML::LibXML->new->parse_string( $xml );
368 $marcxml->documentElement->setNamespace(
369 "http://www.loc.gov/MARC21/slim", "marc", 1 );
370 $marcxml->documentElement->setNamespace("http://www.loc.gov/MARC21/slim");
378 my $override = shift;
379 my $existing_rec = shift || 0;
382 my $marcxml = __make_marc_doc($xml);
384 my $xpath = '//marc:controlfield[@tag="001"]';
385 my $tcn = $marcxml->documentElement->findvalue($xpath);
386 $logger->info("biblio import located 001 (tcn) value of $tcn");
388 $xpath = '//marc:controlfield[@tag="003"]';
389 my $tcn_source = $marcxml->documentElement->findvalue($xpath) || "System Local";
391 if(my $rec = _tcn_exists($editor, $tcn, $tcn_source, $existing_rec) ) {
394 $tcn = find_free_tcn( $marcxml, $editor, $existing_rec );
396 # if we're overriding, try to find a different TCN to use
399 # XXX Create ALLOW_ALT_TCN permission check support
401 $logger->info("tcn value $tcn already exists, attempting to override");
409 'OPEN_TCN_NOT_FOUND',
410 payload => $marcxml->toString())
416 $logger->warn("tcn value $origtcn already exists in import/create");
418 # otherwise, return event
424 'TCN_EXISTS', payload => {
434 return ($tcn, $tcn_source, $marcxml);
441 my $existing_rec = shift;
445 my $xpath = '//marc:datafield[@tag="039"]/subfield[@code="a"]';
446 my ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
447 $xpath = '//marc:datafield[@tag="039"]/subfield[@code="b"]';
448 my $tcn_source = $marcxml->documentElement->findvalue($xpath) || "System Local";
450 if(_tcn_exists($editor, $tcn, $tcn_source, $existing_rec)) {
458 $xpath = '//marc:datafield[@tag="020"]/subfield[@code="a"]';
459 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
460 $tcn_source = "ISBN";
461 if(_tcn_exists($editor, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
465 $xpath = '//marc:datafield[@tag="022"]/subfield[@code="a"]';
466 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
467 $tcn_source = "ISSN";
468 if(_tcn_exists($editor, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
472 $xpath = '//marc:datafield[@tag="010"]';
473 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
474 $tcn_source = "LCCN";
475 if(_tcn_exists($editor, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
479 $xpath = '//marc:datafield[@tag="035"]/subfield[@code="a"]';
480 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
481 $tcn_source = "System Legacy";
482 if(_tcn_exists($editor, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
485 $marcxml->documentElement->removeChild(
486 $marcxml->documentElement->findnodes( '//datafield[@tag="035"]' )
491 return undef unless $tcn;
494 my $df = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'datafield');
495 $df->setAttribute( tag => '039' );
496 $df->setAttribute( ind1 => ' ' );
497 $df->setAttribute( ind2 => ' ' );
498 $marcxml->documentElement->appendChild( $df );
500 my $sfa = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'subfield');
501 $sfa->setAttribute( code => 'a' );
502 $sfa->appendChild( $marcxml->createTextNode( $tcn ) );
503 $df->appendChild( $sfa );
505 my $sfb = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'subfield');
506 $sfb->setAttribute( code => 'b' );
507 $sfb->appendChild( $marcxml->createTextNode( $tcn_source ) );
508 $df->appendChild( $sfb );
520 my $existing_rec = shift || 0;
522 if(!$tcn) {return 0;}
524 $logger->debug("tcn_exists search for tcn $tcn and source $source and id $existing_rec");
526 # XXX why does the source matter?
527 # my $req = $session->request(
528 # { tcn_value => $tcn, tcn_source => $source, deleted => 'f' } );
530 my $recs = $editor->search_biblio_record_entry(
531 {tcn_value => $tcn, deleted => 'f', id => {'!=' => $existing_rec}}, {idlist =>1});
534 $logger->debug("_tcn_exists is true for tcn : $tcn ($source)");
538 $logger->debug("_tcn_exists is false for tcn : $tcn ($source)");
543 __PACKAGE__->register_method(
544 method => "biblio_record_record_metadata",
545 api_name => "open-ils.cat.biblio.record.metadata.retrieve",
547 argc => 1, #(session_id, biblio_tree )
548 notes => "Walks the tree and commits any changed nodes " .
549 "adds any new nodes, and deletes any deleted nodes",
552 sub biblio_record_record_metadata {
553 my( $self, $client, $authtoken, $ids ) = @_;
555 return [] unless $ids and @$ids;
557 my $editor = new_editor(authtoken => $authtoken);
558 return $editor->event unless $editor->checkauth;
559 return $editor->event unless $editor->allowed('VIEW_USER');
564 return $editor->event unless
565 my $rec = $editor->retrieve_biblio_record_entry($_);
566 $rec->creator($editor->retrieve_actor_user($rec->creator));
567 $rec->editor($editor->retrieve_actor_user($rec->editor));
568 $rec->clear_marc; # slim the record down
569 push( @results, $rec );
577 __PACKAGE__->register_method(
578 method => "biblio_record_marc_cn",
579 api_name => "open-ils.cat.biblio.record.marc_cn.retrieve",
580 argc => 1, #(bib id )
583 sub biblio_record_marc_cn {
584 my( $self, $client, $id ) = @_;
586 my $session = OpenSRF::AppSession->create("open-ils.cstore");
588 ->request("open-ils.cstore.direct.biblio.record_entry.retrieve", $id )
592 my $doc = XML::LibXML->new->parse_string($marc);
593 $doc->documentElement->setNamespace( "http://www.loc.gov/MARC21/slim", "marc", 1 );
596 for my $tag ( qw/050 055 060 070 080 082 086 088 090 092 096 098 099/ ) {
597 my @node = $doc->findnodes("//marc:datafield[\@tag='$tag']");
599 my $cn = $x->findvalue("marc:subfield[\@code='a' or \@code='b']");
600 push @res, {$tag => $cn} if ($cn);
607 sub _get_id_by_userid {
612 my $session = OpenSRF::AppSession->create( "open-ils.cstore" );
613 my $request = $session->request(
614 "open-ils.cstore.direct.actor.user.search.atomic", { usrname => \@users } );
616 $request->wait_complete;
617 my $response = $request->recv();
618 if(!$request->complete) {
619 throw OpenSRF::EX::ERROR ("no response from cstore on user retrieve");
622 if(UNIVERSAL::isa( $response, "Error")){
623 throw $response ($response);
626 for my $u (@{$response->content}) {
632 $session->disconnect;
639 # commits metadata objects to the db
640 sub _update_record_metadata {
642 my ($session, @docs ) = @_;
644 for my $doc (@docs) {
646 my $user_obj = $doc->{user};
647 my $docid = $doc->{docid};
649 my $request = $session->request(
650 "open-ils.storage.direct.biblio.record_entry.retrieve", $docid );
651 my $record = $request->gather(1);
653 my ($id) = _get_id_by_userid($user_obj->usrname);
655 $record->editor($id);
657 $request = $session->request(
658 "open-ils.storage.direct.biblio.record_entry.update", $record );
667 __PACKAGE__->register_method(
668 method => "orgs_for_title",
670 api_name => "open-ils.cat.actor.org_unit.retrieve_by_title"
674 my( $self, $client, $record_id ) = @_;
676 my $vols = $apputils->simple_scalar_request(
678 "open-ils.cstore.direct.asset.call_number.search.atomic",
679 { record => $record_id, deleted => 'f' });
681 my $orgs = { map {$_->owning_lib => 1 } @$vols };
682 return [ keys %$orgs ];
686 __PACKAGE__->register_method(
687 method => "retrieve_copies",
689 api_name => "open-ils.cat.asset.copy_tree.retrieve");
691 __PACKAGE__->register_method(
692 method => "retrieve_copies",
693 api_name => "open-ils.cat.asset.copy_tree.global.retrieve");
695 # user_session may be null/undef
696 sub retrieve_copies {
698 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
700 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
704 # grabbing copy trees should be available for everyone..
705 if(!@org_ids and $user_session) {
707 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
708 @org_ids = ($user_obj->home_ou);
711 if( $self->api_name =~ /global/ ) {
712 return _build_volume_list( { record => $docid, deleted => 'f' } );
717 for my $orgid (@org_ids) {
718 my $vols = _build_volume_list(
719 { record => $docid, owning_lib => $orgid, deleted => 'f' } );
720 push( @all_vols, @$vols );
730 sub _build_volume_list {
731 my $search_hash = shift;
733 $search_hash->{deleted} = 'f';
734 my $e = new_editor();
736 my $vols = $e->search_asset_call_number($search_hash);
740 for my $volume (@$vols) {
742 my $copies = $e->search_asset_copy(
743 { call_number => $volume->id , deleted => 'f' });
745 $copies = [ sort { $a->barcode cmp $b->barcode } @$copies ];
747 for my $c (@$copies) {
748 if( $c->status == OILS_COPY_STATUS_CHECKED_OUT ) {
750 $e->search_action_circulation(
752 { target_copy => $c->id },
754 order_by => { circ => 'xact_start desc' },
763 $volume->copies($copies);
764 push( @volumes, $volume );
767 #$session->disconnect();
773 __PACKAGE__->register_method(
774 method => "fleshed_copy_update",
775 api_name => "open-ils.cat.asset.copy.fleshed.batch.update",);
777 __PACKAGE__->register_method(
778 method => "fleshed_copy_update",
779 api_name => "open-ils.cat.asset.copy.fleshed.batch.update.override",);
782 sub fleshed_copy_update {
783 my( $self, $conn, $auth, $copies, $delete_stats ) = @_;
784 return 1 unless ref $copies;
785 my( $reqr, $evt ) = $U->checkses($auth);
787 my $editor = new_editor(requestor => $reqr, xact => 1);
788 my $override = $self->api_name =~ /override/;
789 $evt = update_fleshed_copies($editor, $override, undef, $copies, $delete_stats);
791 $logger->info("fleshed copy update failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
796 $logger->info("fleshed copy update successfully updated ".scalar(@$copies)." copies");
801 __PACKAGE__->register_method(
803 api_name => 'open-ils.cat.biblio.records.merge',
805 Merges a group of records
806 @param auth The login session key
807 @param master The id of the record all other records should be merged into
808 @param records Array of records to be merged into the master record
809 @return 1 on success, Event on error.
814 my( $self, $conn, $auth, $master, $records ) = @_;
815 my( $reqr, $evt ) = $U->checkses($auth);
817 my $editor = new_editor( requestor => $reqr, xact => 1 );
818 my $v = OpenILS::Application::Cat::Merge::merge_records($editor, $master, $records);
821 # tell the client the merge is complete, then merge the holds
822 $conn->respond_complete(1);
823 merge_holds($master, $records);
828 my($master, $records) = @_;
829 return unless $master and @$records;
830 return if @$records == 1 and $master == $$records[0];
832 my $e = new_editor(xact=>1);
833 my $holds = $e->search_action_hold_request(
834 { cancel_time => undef,
835 fulfillment_time => undef,
842 for my $hold_id (@$holds) {
844 my $hold = $e->retrieve_action_hold_request($hold_id);
846 $logger->info("Changing hold ".$hold->id.
847 " target from ".$hold->target." to $master in record merge");
849 $hold->target($master);
850 unless($e->update_action_hold_request($hold)) {
852 $logger->error("Error updating hold ". $evt->textcode .":". $evt->desc .":". $evt->stacktrace);
863 # ---------------------------------------------------------------------------
864 # returns true if the given title (id) has no un-deleted volumes or
865 # copies attached. If a context volume is defined, a record
866 # is considered empty only if the context volume is the only
867 # remaining volume on the record.
868 # ---------------------------------------------------------------------------
870 my( $editor, $rid, $vol_id ) = @_;
872 return 0 if $rid == OILS_PRECAT_RECORD;
874 my $cnlist = $editor->search_asset_call_number(
875 { record => $rid, deleted => 'f' }, { idlist => 1 } );
877 return 1 unless @$cnlist; # no attached volumes
878 return 0 if @$cnlist > 1; # multiple attached volumes
879 return 0 unless $$cnlist[0] == $vol_id; # attached volume is not the context vol.
881 # see if the sole remaining context volume has any attached copies
882 for my $cn (@$cnlist) {
883 my $copylist = $editor->search_asset_copy(
885 { call_number => $cn, deleted => 'f' },
888 return 0 if @$copylist; # false if we find any copies
895 __PACKAGE__->register_method(
896 method => "fleshed_volume_update",
897 api_name => "open-ils.cat.asset.volume.fleshed.batch.update",);
899 __PACKAGE__->register_method(
900 method => "fleshed_volume_update",
901 api_name => "open-ils.cat.asset.volume.fleshed.batch.update.override",);
903 sub fleshed_volume_update {
904 my( $self, $conn, $auth, $volumes, $delete_stats ) = @_;
905 my( $reqr, $evt ) = $U->checkses($auth);
908 my $override = ($self->api_name =~ /override/);
909 my $editor = new_editor( requestor => $reqr, xact => 1 );
911 for my $vol (@$volumes) {
912 $logger->info("vol-update: investigating volume ".$vol->id);
914 $vol->editor($reqr->id);
915 $vol->edit_date('now');
917 my $copies = $vol->copies;
920 $vol->editor($editor->requestor->id);
921 $vol->edit_date('now');
923 if( $vol->isdeleted ) {
925 $logger->info("vol-update: deleting volume");
926 my $cs = $editor->search_asset_copy(
927 { call_number => $vol->id, deleted => 'f' } );
928 return OpenILS::Event->new(
929 'VOLUME_NOT_EMPTY', payload => $vol->id ) if @$cs;
932 return $editor->event unless
933 $editor->update_asset_call_number($vol);
936 } elsif( $vol->isnew ) {
937 $logger->info("vol-update: creating volume");
938 $evt = create_volume( $override, $editor, $vol );
941 } elsif( $vol->ischanged ) {
942 $logger->info("vol-update: update volume");
943 $evt = update_volume($vol, $editor);
947 # now update any attached copies
948 if( $copies and @$copies and !$vol->isdeleted ) {
949 $_->call_number($vol->id) for @$copies;
950 $evt = update_fleshed_copies( $editor, $override, $vol, $copies, $delete_stats );
956 return scalar(@$volumes);
965 return $evt if ( $evt = org_cannot_have_vols($editor, $vol->owning_lib) );
967 my $vols = $editor->search_asset_call_number( {
968 owning_lib => $vol->owning_lib,
969 record => $vol->record,
970 label => $vol->label,
975 # There exists a different volume in the DB with the same properties
976 return OpenILS::Event->new('VOLUME_LABEL_EXISTS', payload => $vol->id)
977 if grep { $_->id ne $vol->id } @$vols;
979 return $editor->event unless $editor->update_asset_call_number($vol);
986 my( $vol, $copy ) = @_;
987 my $org = $vol->owning_lib;
988 if( $vol->id == OILS_PRECAT_CALL_NUMBER ) {
989 $org = ref($copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
991 $logger->debug("using copy perm org $org");
996 # this does the actual work
997 sub update_fleshed_copies {
998 my( $editor, $override, $vol, $copies, $delete_stats ) = @_;
1001 my $fetchvol = ($vol) ? 0 : 1;
1004 $cache{$vol->id} = $vol if $vol;
1006 for my $copy (@$copies) {
1008 my $copyid = $copy->id;
1009 $logger->info("vol-update: inspecting copy $copyid");
1011 if( !($vol = $cache{$copy->call_number}) ) {
1012 $vol = $cache{$copy->call_number} =
1013 $editor->retrieve_asset_call_number($copy->call_number);
1014 return $editor->event unless $vol;
1017 return $editor->event unless
1018 $editor->allowed('UPDATE_COPY', copy_perm_org($vol, $copy));
1020 $copy->editor($editor->requestor->id);
1021 $copy->edit_date('now');
1023 $copy->status( $copy->status->id ) if ref($copy->status);
1024 $copy->location( $copy->location->id ) if ref($copy->location);
1025 $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
1027 my $sc_entries = $copy->stat_cat_entries;
1028 $copy->clear_stat_cat_entries;
1030 if( $copy->isdeleted ) {
1031 $evt = delete_copy($editor, $override, $vol, $copy);
1032 return $evt if $evt;
1034 } elsif( $copy->isnew ) {
1035 $evt = create_copy( $editor, $vol, $copy );
1036 return $evt if $evt;
1038 } elsif( $copy->ischanged ) {
1040 $evt = update_copy( $editor, $override, $vol, $copy );
1041 return $evt if $evt;
1044 $copy->stat_cat_entries( $sc_entries );
1045 $evt = update_copy_stat_entries($editor, $copy, $delete_stats);
1046 return $evt if $evt;
1049 $logger->debug("vol-update: done updating copy batch");
1054 sub fix_copy_price {
1057 if(defined $copy->price) {
1058 my $p = $copy->price || 0;
1063 my $d = $copy->deposit_amount || 0;
1065 $copy->deposit_amount($d);
1070 my( $editor, $override, $vol, $copy ) = @_;
1073 my $org = (ref $copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
1074 return $evt if ( $evt = org_cannot_have_vols($editor, $org) );
1076 $logger->info("vol-update: updating copy ".$copy->id);
1077 my $orig_copy = $editor->retrieve_asset_copy($copy->id);
1078 my $orig_vol = $editor->retrieve_asset_call_number($copy->call_number);
1080 $copy->editor($editor->requestor->id);
1081 $copy->edit_date('now');
1083 $copy->age_protect( $copy->age_protect->id )
1084 if ref $copy->age_protect;
1086 fix_copy_price($copy);
1088 return $editor->event unless $editor->update_asset_copy($copy);
1089 return remove_empty_objects($editor, $override, $orig_vol);
1093 sub remove_empty_objects {
1094 my( $editor, $override, $vol ) = @_;
1096 my $koe = $U->ou_ancestor_setting_value(
1097 $editor->requestor->ws_ou, 'cat.bib.keep_on_empty', $editor);
1098 my $aoe = $U->ou_ancestor_setting_value(
1099 $editor->requestor->ws_ou, 'cat.bib.alert_on_empty', $editor);
1101 if( title_is_empty($editor, $vol->record, $vol->id) ) {
1103 # delete this volume if it's not already marked as deleted
1104 unless( $U->is_true($vol->deleted) || $vol->isdeleted ) {
1106 $vol->editor($editor->requestor->id);
1107 $vol->edit_date('now');
1108 $editor->update_asset_call_number($vol) or return $editor->event;
1112 # delete the bib record if the keep-on-empty setting is not set
1113 my $evt = delete_rec($editor, $vol->record);
1114 return $evt if $evt;
1117 # return the empty alert if the alert-on-empty setting is set
1118 return OpenILS::Event->new('TITLE_LAST_COPY', payload => $vol->record ) if $aoe;
1125 __PACKAGE__->register_method (
1126 method => 'delete_bib_record',
1127 api_name => 'open-ils.cat.biblio.record_entry.delete');
1129 sub delete_bib_record {
1130 my($self, $conn, $auth, $rec_id) = @_;
1131 my $e = new_editor(xact=>1, authtoken=>$auth);
1132 return $e->die_event unless $e->checkauth;
1133 return $e->die_event unless $e->allowed('DELETE_RECORD', $e->requestor->ws_ou);
1134 my $vols = $e->search_asset_call_number({record=>$rec_id, deleted=>'f'});
1135 return OpenILS::Event->new('RECORD_NOT_EMPTY', payload=>$rec_id) if @$vols;
1136 my $evt = delete_rec($e, $rec_id);
1137 if($evt) { $e->rollback; return $evt; }
1143 # marks a record as deleted
1145 my( $editor, $rec_id ) = @_;
1147 my $rec = $editor->retrieve_biblio_record_entry($rec_id)
1148 or return $editor->event;
1150 return undef if $U->is_true($rec->deleted);
1154 $rec->editor( $editor->requestor->id );
1155 $rec->edit_date('now');
1156 $editor->update_biblio_record_entry($rec) or return $editor->event;
1163 my( $editor, $override, $vol, $copy ) = @_;
1165 return $editor->event unless
1166 $editor->allowed('DELETE_COPY',copy_perm_org($vol, $copy));
1168 my $stat = $U->copy_status($copy->status)->id;
1171 return OpenILS::Event->new('COPY_DELETE_WARNING', payload => $copy->id )
1172 if $stat == OILS_COPY_STATUS_CHECKED_OUT or
1173 $stat == OILS_COPY_STATUS_IN_TRANSIT or
1174 $stat == OILS_COPY_STATUS_ON_HOLDS_SHELF or
1175 $stat == OILS_COPY_STATUS_ILL;
1178 $logger->info("vol-update: deleting copy ".$copy->id);
1179 $copy->deleted('t');
1181 $copy->editor($editor->requestor->id);
1182 $copy->edit_date('now');
1183 $editor->update_asset_copy($copy) or return $editor->event;
1185 # Delete any open transits for this copy
1186 my $transits = $editor->search_action_transit_copy(
1187 { target_copy=>$copy->id, dest_recv_time => undef } );
1189 for my $t (@$transits) {
1190 $editor->delete_action_transit_copy($t)
1191 or return $editor->event;
1194 return remove_empty_objects($editor, $override, $vol);
1199 my( $editor, $vol, $copy ) = @_;
1201 my $existing = $editor->search_asset_copy(
1202 { barcode => $copy->barcode, deleted => 'f' } );
1204 return OpenILS::Event->new('ITEM_BARCODE_EXISTS') if @$existing;
1206 # see if the volume this copy references is marked as deleted
1207 my $evol = $editor->retrieve_asset_call_number($copy->call_number)
1208 or return $editor->event;
1209 return OpenILS::Event->new('VOLUME_DELETED', vol => $evol->id)
1210 if $U->is_true($evol->deleted);
1213 my $org = (ref $copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
1214 return $evt if ( $evt = org_cannot_have_vols($editor, $org) );
1217 $copy->creator($editor->requestor->id);
1218 $copy->create_date('now');
1219 fix_copy_price($copy);
1221 $editor->create_asset_copy($copy) or return $editor->event;
1225 # if 'delete_stats' is true, the copy->stat_cat_entries data is
1226 # treated as the authoritative list for the copy. existing entries
1227 # that are not in said list will be deleted from the DB
1228 sub update_copy_stat_entries {
1229 my( $editor, $copy, $delete_stats ) = @_;
1231 return undef if $copy->isdeleted;
1232 return undef unless $copy->ischanged or $copy->isnew;
1235 my $entries = $copy->stat_cat_entries;
1237 if( $delete_stats ) {
1238 $entries = ($entries and @$entries) ? $entries : [];
1240 return undef unless ($entries and @$entries);
1243 my $maps = $editor->search_asset_stat_cat_entry_copy_map({owning_copy=>$copy->id});
1246 # if there is no stat cat entry on the copy who's id matches the
1247 # current map's id, remove the map from the database
1248 for my $map (@$maps) {
1249 if(! grep { $_->id == $map->stat_cat_entry } @$entries ) {
1251 $logger->info("copy update found stale ".
1252 "stat cat entry map ".$map->id. " on copy ".$copy->id);
1254 $editor->delete_asset_stat_cat_entry_copy_map($map)
1255 or return $editor->event;
1260 # go through the stat cat update/create process
1261 for my $entry (@$entries) {
1264 # if this link already exists in the DB, don't attempt to re-create it
1265 next if( grep{$_->stat_cat_entry == $entry->id} @$maps );
1267 my $new_map = Fieldmapper::asset::stat_cat_entry_copy_map->new();
1269 my $sc = ref($entry->stat_cat) ? $entry->stat_cat->id : $entry->stat_cat;
1271 $new_map->stat_cat( $sc );
1272 $new_map->stat_cat_entry( $entry->id );
1273 $new_map->owning_copy( $copy->id );
1275 $editor->create_asset_stat_cat_entry_copy_map($new_map)
1276 or return $editor->event;
1278 $logger->info("copy update created new stat cat entry map ".$editor->data);
1286 my( $override, $editor, $vol ) = @_;
1289 return $evt if ( $evt = org_cannot_have_vols($editor, $vol->owning_lib) );
1291 # see if the record this volume references is marked as deleted
1292 my $rec = $editor->retrieve_biblio_record_entry($vol->record)
1293 or return $editor->event;
1294 return OpenILS::Event->new('BIB_RECORD_DELETED', rec => $rec->id)
1295 if $U->is_true($rec->deleted);
1297 # first lets see if there are any collisions
1298 my $vols = $editor->search_asset_call_number( {
1299 owning_lib => $vol->owning_lib,
1300 record => $vol->record,
1301 label => $vol->label,
1308 # we've found an exising volume
1310 $label = $vol->label;
1312 return OpenILS::Event->new(
1313 'VOLUME_LABEL_EXISTS', payload => $vol->id);
1317 # create a temp label so we can create the new volume,
1318 # then de-dup it with the existing volume
1319 $vol->label( "__SYSTEM_TMP_$$".time) if $label;
1321 $vol->creator($editor->requestor->id);
1322 $vol->create_date('now');
1323 $vol->editor($editor->requestor->id);
1324 $vol->edit_date('now');
1327 $editor->create_asset_call_number($vol) or return $editor->event;
1330 # now restore the label and merge into the existing record
1331 $vol->label($label);
1333 OpenILS::Application::Cat::Merge::merge_volumes($editor, [$vol], $$vols[0]);
1334 return $evt if $evt;
1341 __PACKAGE__->register_method (
1342 method => 'batch_volume_transfer',
1343 api_name => 'open-ils.cat.asset.volume.batch.transfer',
1346 __PACKAGE__->register_method (
1347 method => 'batch_volume_transfer',
1348 api_name => 'open-ils.cat.asset.volume.batch.transfer.override',
1352 sub batch_volume_transfer {
1353 my( $self, $conn, $auth, $args ) = @_;
1356 my $rec = $$args{docid};
1357 my $o_lib = $$args{lib};
1358 my $vol_ids = $$args{volumes};
1360 my $override = 1 if $self->api_name =~ /override/;
1362 $logger->info("merge: transferring volumes to lib=$o_lib and record=$rec");
1364 my $e = new_editor(authtoken => $auth, xact =>1);
1365 return $e->event unless $e->checkauth;
1366 return $e->event unless $e->allowed('UPDATE_VOLUME', $o_lib);
1368 my $dorg = $e->retrieve_actor_org_unit($o_lib)
1369 or return $e->event;
1371 my $ou_type = $e->retrieve_actor_org_unit_type($dorg->ou_type)
1372 or return $e->event;
1374 return $evt if ( $evt = org_cannot_have_vols($e, $o_lib) );
1376 my $vols = $e->batch_retrieve_asset_call_number($vol_ids);
1381 for my $vol (@$vols) {
1383 # if we've already looked at this volume, go to the next
1384 next if !$vol or grep { $vol->id == $_ } @seen;
1386 # grab all of the volumes in the list that have
1387 # the same label so they can be merged
1388 my @all = grep { $_->label eq $vol->label } @$vols;
1390 # take note of the fact that we've looked at this set of volumes
1391 push( @seen, $_->id ) for @all;
1392 push( @rec_ids, $_->record ) for @all;
1394 # for each volume, see if there are any copies that have a
1395 # remote circ_lib (circ_lib != vol->owning_lib and != $o_lib ).
1397 unless( $override ) {
1400 $logger->debug("merge: searching for copies with remote circ_lib for volume ".$v->id);
1402 call_number => $v->id,
1403 circ_lib => { "not in" => [ $o_lib, $v->owning_lib ] },
1407 my $copies = $e->search_asset_copy($args, {idlist=>1});
1409 # if the copy's circ_lib matches the destination lib,
1411 return OpenILS::Event->new('COPY_REMOTE_CIRC_LIB') if @$copies;
1415 # see if there is a volume at the destination lib that
1416 # already has the requested label
1417 my $existing_vol = $e->search_asset_call_number(
1419 label => $vol->label,
1421 owning_lib =>$o_lib,
1426 if( $existing_vol ) {
1428 if( grep { $_->id == $existing_vol->id } @all ) {
1429 # this volume is already accounted for in our list of volumes to merge
1430 $existing_vol = undef;
1433 # this volume exists on the destination record/owning_lib and must
1434 # be used as the destination for merging
1435 $logger->debug("merge: volume already exists at destination record: ".
1436 $existing_vol->id.' : '.$existing_vol->label) if $existing_vol;
1440 if( @all > 1 || $existing_vol ) {
1441 $logger->info("merge: found collisions in volume transfer");
1442 my @args = ($e, \@all);
1443 @args = ($e, \@all, $existing_vol) if $existing_vol;
1444 ($vol, $evt) = OpenILS::Application::Cat::Merge::merge_volumes(@args);
1445 return $evt if $evt;
1448 if( !$existing_vol ) {
1450 $vol->owning_lib($o_lib);
1452 $vol->editor($e->requestor->id);
1453 $vol->edit_date('now');
1455 $logger->info("merge: updating volume ".$vol->id);
1456 $e->update_asset_call_number($vol) or return $e->event;
1459 $logger->info("merge: bypassing volume update because existing volume used as target");
1462 # regardless of what volume was used as the destination,
1463 # update any copies that have moved over to the new lib
1464 my $copies = $e->search_asset_copy({call_number=>$vol->id, deleted => 'f'});
1466 # update circ lib on the copies - make this a method flag?
1467 for my $copy (@$copies) {
1468 next if $copy->circ_lib == $o_lib;
1469 $logger->info("merge: transfer moving circ lib on copy ".$copy->id);
1470 $copy->circ_lib($o_lib);
1471 $copy->editor($e->requestor->id);
1472 $copy->edit_date('now');
1473 $e->update_asset_copy($copy) or return $e->event;
1476 # Now see if any empty records need to be deleted after all of this
1479 $logger->debug("merge: seeing if we should delete record $_...");
1480 $evt = delete_rec($e, $_) if title_is_empty($e, $_);
1481 return $evt if $evt;
1485 # $evt = remove_empty_objects($e, $override, $_);
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;
1527 if($record_id == OILS_PRECAT_RECORD) {
1529 $vol = $e->retrieve_asset_call_number(OILS_PRECAT_CALL_NUMBER)
1530 or return $e->die_event;
1534 $vol = $e->search_asset_call_number(
1535 {label => $label, record => $record_id, owning_lib => $org_id, deleted => 'f'},
1540 # If the volume exists, return the ID
1541 if( $vol ) { $e->rollback; return $vol; }
1543 # -----------------------------------------------------------------
1544 # Otherwise, create a new volume with the given attributes
1545 # -----------------------------------------------------------------
1547 return $e->die_event unless $e->allowed('UPDATE_VOLUME', $org_id);
1549 $vol = Fieldmapper::asset::call_number->new;
1550 $vol->owning_lib($org_id);
1551 $vol->label($label);
1552 $vol->record($record_id);
1554 my $evt = create_volume( 0, $e, $vol );
1555 return $evt if $evt;