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', $e->requestor->ws_ou);
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) if ($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 );
249 __PACKAGE__->register_method(
250 method => "update_biblio_record_entry",
251 api_name => "open-ils.cat.biblio.record_entry.update",
253 Updates a biblio.record_entry
254 @param auth The authtoken
255 @param record The record with updated values
256 @return 1 on success, Event on error.
260 sub update_biblio_record_entry {
261 my($self, $conn, $auth, $record) = @_;
262 my $e = new_editor(authtoken=>$auth, xact=>1);
263 return $e->die_event unless $e->checkauth;
264 return $e->die_event unless $e->allowed('UPDATE_RECORD');
265 $e->update_biblio_record_entry($record) or return $e->die_event;
270 __PACKAGE__->register_method(
271 method => "undelete_biblio_record_entry",
272 api_name => "open-ils.cat.biblio.record_entry.undelete",
274 Un-deletes a record and sets active=true
275 @param auth The authtoken
276 @param record The record_id to ressurect
277 @return 1 on success, Event on error.
280 sub undelete_biblio_record_entry {
281 my($self, $conn, $auth, $record_id) = @_;
282 my $e = new_editor(authtoken=>$auth, xact=>1);
283 return $e->die_event unless $e->checkauth;
284 return $e->die_event unless $e->allowed('UPDATE_RECORD');
286 my $record = $e->retrieve_biblio_record_entry($record_id)
287 or return $e->die_event;
288 $record->deleted('f');
289 $record->active('t');
291 # no 2 non-deleted records can have the same tcn_value
292 my $existing = $e->search_biblio_record_entry(
294 tcn_value => $record->tcn_value,
295 id => {'!=' => $record_id}
297 return OpenILS::Event->new('TCN_EXISTS') if @$existing;
299 $e->update_biblio_record_entry($record) or return $e->die_event;
305 __PACKAGE__->register_method(
306 method => "biblio_record_xml_import",
307 api_name => "open-ils.cat.biblio.record.xml.import.override",
308 signature => q/@see open-ils.cat.biblio.record.xml.import/);
310 __PACKAGE__->register_method(
311 method => "biblio_record_xml_import",
312 api_name => "open-ils.cat.biblio.record.xml.import",
313 notes => <<" NOTES");
314 Takes a marcxml record and imports the record into the database. In this
315 case, the marcxml record is assumed to be a complete record (i.e. valid
316 MARC). The title control number is taken from (whichever comes first)
317 tags 001, 039[ab], 020a, 022a, 010, 035a and whichever does not already exist
319 user_session must have IMPORT_MARC permissions
323 sub biblio_record_xml_import {
324 my( $self, $client, $authtoken, $xml, $source, $auto_tcn) = @_;
326 my $override = 1 if $self->api_name =~ /override/;
327 my $e = new_editor(xact=>1, authtoken=>$authtoken);
328 return $e->die_event unless $e->checkauth;
329 return $e->die_event unless $e->allowed('IMPORT_MARC', $e->requestor->ws_ou);
331 my( $evt, $tcn, $tcn_source, $marcdoc );
334 # auto_tcn forces a blank TCN value so the DB will have to generate one for us
335 $marcdoc = __make_marc_doc($xml);
337 ( $tcn, $tcn_source, $marcdoc, $evt ) = _find_tcn_info($e, $xml, $override);
341 $logger->info("user ".$e->requestor->id.
342 " creating new biblio entry with tcn=$tcn and tcn_source $tcn_source");
344 my $record = Fieldmapper::biblio::record_entry->new;
346 $record->source(bib_source_from_name($source)) if $source;
347 $record->tcn_source($tcn_source);
348 $record->tcn_value($tcn) if ($tcn);
349 $record->creator($e->requestor->id);
350 $record->editor($e->requestor->id);
351 $record->create_date('now');
352 $record->edit_date('now');
353 $record->marc( entityize( $marcdoc->documentElement->toString ) );
355 $record = $e->create_biblio_record_entry($record) or return $e->die_event;
356 $logger->info("marc create/import created new record ".$record->id);
360 $logger->debug("Sending record off to be ingested and indexed");
362 $client->respond_complete($record);
366 'open-ils.ingest.full.biblio.record', $record->id );
371 sub __make_marc_doc {
373 my $marcxml = XML::LibXML->new->parse_string( $xml );
374 $marcxml->documentElement->setNamespace(
375 "http://www.loc.gov/MARC21/slim", "marc", 1 );
376 $marcxml->documentElement->setNamespace("http://www.loc.gov/MARC21/slim");
384 my $override = shift;
385 my $existing_rec = shift || 0;
388 my $marcxml = __make_marc_doc($xml);
390 my $xpath = '//marc:controlfield[@tag="001"]';
391 my $tcn = $marcxml->documentElement->findvalue($xpath);
392 $logger->info("biblio import located 001 (tcn) value of $tcn");
394 $xpath = '//marc:controlfield[@tag="003"]';
395 my $tcn_source = $marcxml->documentElement->findvalue($xpath) || "System Local";
397 if(my $rec = _tcn_exists($editor, $tcn, $tcn_source, $existing_rec) ) {
400 $tcn = find_free_tcn( $marcxml, $editor, $existing_rec );
402 # if we're overriding, try to find a different TCN to use
405 # XXX Create ALLOW_ALT_TCN permission check support
407 $logger->info("tcn value $tcn already exists, attempting to override");
415 'OPEN_TCN_NOT_FOUND',
416 payload => $marcxml->toString())
422 $logger->warn("tcn value $origtcn already exists in import/create");
424 # otherwise, return event
430 'TCN_EXISTS', payload => {
440 return ($tcn, $tcn_source, $marcxml);
447 my $existing_rec = shift;
451 my $xpath = '//marc:datafield[@tag="039"]/subfield[@code="a"]';
452 my ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
453 $xpath = '//marc:datafield[@tag="039"]/subfield[@code="b"]';
454 my $tcn_source = $marcxml->documentElement->findvalue($xpath) || "System Local";
456 if(_tcn_exists($editor, $tcn, $tcn_source, $existing_rec)) {
464 $xpath = '//marc:datafield[@tag="020"]/subfield[@code="a"]';
465 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
466 $tcn_source = "ISBN";
467 if(_tcn_exists($editor, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
471 $xpath = '//marc:datafield[@tag="022"]/subfield[@code="a"]';
472 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
473 $tcn_source = "ISSN";
474 if(_tcn_exists($editor, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
478 $xpath = '//marc:datafield[@tag="010"]';
479 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
480 $tcn_source = "LCCN";
481 if(_tcn_exists($editor, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
485 $xpath = '//marc:datafield[@tag="035"]/subfield[@code="a"]';
486 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
487 $tcn_source = "System Legacy";
488 if(_tcn_exists($editor, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
491 $marcxml->documentElement->removeChild(
492 $marcxml->documentElement->findnodes( '//datafield[@tag="035"]' )
497 return undef unless $tcn;
500 my $df = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'datafield');
501 $df->setAttribute( tag => '039' );
502 $df->setAttribute( ind1 => ' ' );
503 $df->setAttribute( ind2 => ' ' );
504 $marcxml->documentElement->appendChild( $df );
506 my $sfa = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'subfield');
507 $sfa->setAttribute( code => 'a' );
508 $sfa->appendChild( $marcxml->createTextNode( $tcn ) );
509 $df->appendChild( $sfa );
511 my $sfb = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'subfield');
512 $sfb->setAttribute( code => 'b' );
513 $sfb->appendChild( $marcxml->createTextNode( $tcn_source ) );
514 $df->appendChild( $sfb );
526 my $existing_rec = shift || 0;
528 if(!$tcn) {return 0;}
530 $logger->debug("tcn_exists search for tcn $tcn and source $source and id $existing_rec");
532 # XXX why does the source matter?
533 # my $req = $session->request(
534 # { tcn_value => $tcn, tcn_source => $source, deleted => 'f' } );
536 my $recs = $editor->search_biblio_record_entry(
537 {tcn_value => $tcn, deleted => 'f', id => {'!=' => $existing_rec}}, {idlist =>1});
540 $logger->debug("_tcn_exists is true for tcn : $tcn ($source)");
544 $logger->debug("_tcn_exists is false for tcn : $tcn ($source)");
549 __PACKAGE__->register_method(
550 method => "biblio_record_record_metadata",
551 api_name => "open-ils.cat.biblio.record.metadata.retrieve",
553 argc => 1, #(session_id, biblio_tree )
554 notes => "Walks the tree and commits any changed nodes " .
555 "adds any new nodes, and deletes any deleted nodes",
558 sub biblio_record_record_metadata {
559 my( $self, $client, $authtoken, $ids ) = @_;
561 return [] unless $ids and @$ids;
563 my $editor = new_editor(authtoken => $authtoken);
564 return $editor->event unless $editor->checkauth;
565 return $editor->event unless $editor->allowed('VIEW_USER');
570 return $editor->event unless
571 my $rec = $editor->retrieve_biblio_record_entry($_);
572 $rec->creator($editor->retrieve_actor_user($rec->creator));
573 $rec->editor($editor->retrieve_actor_user($rec->editor));
574 $rec->clear_marc; # slim the record down
575 push( @results, $rec );
583 __PACKAGE__->register_method(
584 method => "biblio_record_marc_cn",
585 api_name => "open-ils.cat.biblio.record.marc_cn.retrieve",
586 argc => 1, #(bib id )
589 sub biblio_record_marc_cn {
590 my( $self, $client, $id ) = @_;
592 my $session = OpenSRF::AppSession->create("open-ils.cstore");
594 ->request("open-ils.cstore.direct.biblio.record_entry.retrieve", $id )
598 my $doc = XML::LibXML->new->parse_string($marc);
599 $doc->documentElement->setNamespace( "http://www.loc.gov/MARC21/slim", "marc", 1 );
602 for my $tag ( qw/050 055 060 070 080 082 086 088 090 092 096 098 099/ ) {
603 my @node = $doc->findnodes("//marc:datafield[\@tag='$tag']");
605 my $cn = $x->findvalue("marc:subfield[\@code='a' or \@code='b']");
606 push @res, {$tag => $cn} if ($cn);
613 sub _get_id_by_userid {
618 my $session = OpenSRF::AppSession->create( "open-ils.cstore" );
619 my $request = $session->request(
620 "open-ils.cstore.direct.actor.user.search.atomic", { usrname => \@users } );
622 $request->wait_complete;
623 my $response = $request->recv();
624 if(!$request->complete) {
625 throw OpenSRF::EX::ERROR ("no response from cstore on user retrieve");
628 if(UNIVERSAL::isa( $response, "Error")){
629 throw $response ($response);
632 for my $u (@{$response->content}) {
638 $session->disconnect;
645 # commits metadata objects to the db
646 sub _update_record_metadata {
648 my ($session, @docs ) = @_;
650 for my $doc (@docs) {
652 my $user_obj = $doc->{user};
653 my $docid = $doc->{docid};
655 warn "Updating metata for doc $docid\n";
657 my $request = $session->request(
658 "open-ils.storage.direct.biblio.record_entry.retrieve", $docid );
659 my $record = $request->gather(1);
661 warn "retrieved record\n";
662 my ($id) = _get_id_by_userid($user_obj->usrname);
664 warn "got $id from _get_id_by_userid\n";
665 $record->editor($id);
667 warn "Grabbed the record, updating and moving on\n";
669 $request = $session->request(
670 "open-ils.storage.direct.biblio.record_entry.update", $record );
674 warn "committing metarecord update\n";
681 __PACKAGE__->register_method(
682 method => "orgs_for_title",
684 api_name => "open-ils.cat.actor.org_unit.retrieve_by_title"
688 my( $self, $client, $record_id ) = @_;
690 my $vols = $apputils->simple_scalar_request(
692 "open-ils.cstore.direct.asset.call_number.search.atomic",
693 { record => $record_id, deleted => 'f' });
695 my $orgs = { map {$_->owning_lib => 1 } @$vols };
696 return [ keys %$orgs ];
700 __PACKAGE__->register_method(
701 method => "retrieve_copies",
703 api_name => "open-ils.cat.asset.copy_tree.retrieve");
705 __PACKAGE__->register_method(
706 method => "retrieve_copies",
707 api_name => "open-ils.cat.asset.copy_tree.global.retrieve");
709 # user_session may be null/undef
710 sub retrieve_copies {
712 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
714 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
718 warn " $$ retrieving copy tree for orgs @org_ids and doc $docid at " . time() . "\n";
720 # grabbing copy trees should be available for everyone..
721 if(!@org_ids and $user_session) {
723 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
724 @org_ids = ($user_obj->home_ou);
727 if( $self->api_name =~ /global/ ) {
728 warn "performing global copy_tree search for $docid\n";
729 return _build_volume_list( { record => $docid, deleted => 'f' } );
734 for my $orgid (@org_ids) {
735 my $vols = _build_volume_list(
736 { record => $docid, owning_lib => $orgid, deleted => 'f' } );
737 warn "Volumes built for org $orgid\n";
738 push( @all_vols, @$vols );
741 warn " $$ Finished copy_tree at " . time() . "\n";
749 sub _build_volume_list {
750 my $search_hash = shift;
752 $search_hash->{deleted} = 'f';
753 my $e = new_editor();
755 my $vols = $e->search_asset_call_number($search_hash);
759 for my $volume (@$vols) {
761 my $copies = $e->search_asset_copy(
762 { call_number => $volume->id , deleted => 'f' });
764 $copies = [ sort { $a->barcode cmp $b->barcode } @$copies ];
766 for my $c (@$copies) {
767 if( $c->status == OILS_COPY_STATUS_CHECKED_OUT ) {
769 $e->search_action_circulation(
771 { target_copy => $c->id },
773 order_by => { circ => 'xact_start desc' },
782 $volume->copies($copies);
783 push( @volumes, $volume );
786 #$session->disconnect();
792 __PACKAGE__->register_method(
793 method => "fleshed_copy_update",
794 api_name => "open-ils.cat.asset.copy.fleshed.batch.update",);
796 __PACKAGE__->register_method(
797 method => "fleshed_copy_update",
798 api_name => "open-ils.cat.asset.copy.fleshed.batch.update.override",);
801 sub fleshed_copy_update {
802 my( $self, $conn, $auth, $copies, $delete_stats ) = @_;
803 return 1 unless ref $copies;
804 my( $reqr, $evt ) = $U->checkses($auth);
806 my $editor = new_editor(requestor => $reqr, xact => 1);
807 my $override = $self->api_name =~ /override/;
808 $evt = update_fleshed_copies($editor, $override, undef, $copies, $delete_stats);
810 $logger->info("fleshed copy update failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
815 $logger->info("fleshed copy update successfully updated ".scalar(@$copies)." copies");
820 __PACKAGE__->register_method(
822 api_name => 'open-ils.cat.biblio.records.merge',
824 Merges a group of records
825 @param auth The login session key
826 @param master The id of the record all other records should be merged into
827 @param records Array of records to be merged into the master record
828 @return 1 on success, Event on error.
833 my( $self, $conn, $auth, $master, $records ) = @_;
834 my( $reqr, $evt ) = $U->checkses($auth);
836 my $editor = new_editor( requestor => $reqr, xact => 1 );
837 my $v = OpenILS::Application::Cat::Merge::merge_records($editor, $master, $records);
840 # tell the client the merge is complete, then merge the holds
841 $conn->respond_complete(1);
842 merge_holds($master, $records);
847 my($master, $records) = @_;
848 return unless $master and @$records;
849 return if @$records == 1 and $master == $$records[0];
851 my $e = new_editor(xact=>1);
852 my $holds = $e->search_action_hold_request(
853 { cancel_time => undef,
854 fulfillment_time => undef,
861 for my $hold_id (@$holds) {
863 my $hold = $e->retrieve_action_hold_request($hold_id);
865 $logger->info("Changing hold ".$hold->id.
866 " target from ".$hold->target." to $master in record merge");
868 $hold->target($master);
869 unless($e->update_action_hold_request($hold)) {
871 $logger->error("Error updating hold ". $evt->textcode .":". $evt->desc .":". $evt->stacktrace);
882 # ---------------------------------------------------------------------------
883 # returns true if the given title (id) has no un-deleted volumes or
884 # copies attached. If a context volume is defined, a record
885 # is considered empty only if the context volume is the only
886 # remaining volume on the record.
887 # ---------------------------------------------------------------------------
889 my( $editor, $rid, $vol_id ) = @_;
891 return 0 if $rid == OILS_PRECAT_RECORD;
893 my $cnlist = $editor->search_asset_call_number(
894 { record => $rid, deleted => 'f' }, { idlist => 1 } );
896 return 1 unless @$cnlist; # no attached volumes
897 return 0 if @$cnlist > 1; # multiple attached volumes
898 return 0 unless $$cnlist[0] == $vol_id; # attached volume is not the context vol.
900 # see if the sole remaining context volume has any attached copies
901 for my $cn (@$cnlist) {
902 my $copylist = $editor->search_asset_copy(
904 { call_number => $cn, deleted => 'f' },
907 return 0 if @$copylist; # false if we find any copies
914 __PACKAGE__->register_method(
915 method => "fleshed_volume_update",
916 api_name => "open-ils.cat.asset.volume.fleshed.batch.update",);
918 __PACKAGE__->register_method(
919 method => "fleshed_volume_update",
920 api_name => "open-ils.cat.asset.volume.fleshed.batch.update.override",);
922 sub fleshed_volume_update {
923 my( $self, $conn, $auth, $volumes, $delete_stats ) = @_;
924 my( $reqr, $evt ) = $U->checkses($auth);
927 my $override = ($self->api_name =~ /override/);
928 my $editor = new_editor( requestor => $reqr, xact => 1 );
930 for my $vol (@$volumes) {
931 $logger->info("vol-update: investigating volume ".$vol->id);
933 $vol->editor($reqr->id);
934 $vol->edit_date('now');
936 my $copies = $vol->copies;
939 $vol->editor($editor->requestor->id);
940 $vol->edit_date('now');
942 if( $vol->isdeleted ) {
944 $logger->info("vol-update: deleting volume");
945 my $cs = $editor->search_asset_copy(
946 { call_number => $vol->id, deleted => 'f' } );
947 return OpenILS::Event->new(
948 'VOLUME_NOT_EMPTY', payload => $vol->id ) if @$cs;
951 return $editor->event unless
952 $editor->update_asset_call_number($vol);
955 } elsif( $vol->isnew ) {
956 $logger->info("vol-update: creating volume");
957 $evt = create_volume( $override, $editor, $vol );
960 } elsif( $vol->ischanged ) {
961 $logger->info("vol-update: update volume");
962 $evt = update_volume($vol, $editor);
966 # now update any attached copies
967 if( $copies and @$copies and !$vol->isdeleted ) {
968 $_->call_number($vol->id) for @$copies;
969 $evt = update_fleshed_copies( $editor, $override, $vol, $copies, $delete_stats );
975 return scalar(@$volumes);
984 return $evt if ( $evt = org_cannot_have_vols($editor, $vol->owning_lib) );
986 my $vols = $editor->search_asset_call_number( {
987 owning_lib => $vol->owning_lib,
988 record => $vol->record,
989 label => $vol->label,
994 # There exists a different volume in the DB with the same properties
995 return OpenILS::Event->new('VOLUME_LABEL_EXISTS', payload => $vol->id)
996 if grep { $_->id ne $vol->id } @$vols;
998 return $editor->event unless $editor->update_asset_call_number($vol);
1005 my( $vol, $copy ) = @_;
1006 my $org = $vol->owning_lib;
1007 if( $vol->id == OILS_PRECAT_CALL_NUMBER ) {
1008 $org = ref($copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
1010 $logger->debug("using copy perm org $org");
1015 # this does the actual work
1016 sub update_fleshed_copies {
1017 my( $editor, $override, $vol, $copies, $delete_stats ) = @_;
1020 my $fetchvol = ($vol) ? 0 : 1;
1023 $cache{$vol->id} = $vol if $vol;
1025 for my $copy (@$copies) {
1027 my $copyid = $copy->id;
1028 $logger->info("vol-update: inspecting copy $copyid");
1030 if( !($vol = $cache{$copy->call_number}) ) {
1031 $vol = $cache{$copy->call_number} =
1032 $editor->retrieve_asset_call_number($copy->call_number);
1033 return $editor->event unless $vol;
1036 return $editor->event unless
1037 $editor->allowed('UPDATE_COPY', copy_perm_org($vol, $copy));
1039 $copy->editor($editor->requestor->id);
1040 $copy->edit_date('now');
1042 $copy->status( $copy->status->id ) if ref($copy->status);
1043 $copy->location( $copy->location->id ) if ref($copy->location);
1044 $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
1046 my $sc_entries = $copy->stat_cat_entries;
1047 $copy->clear_stat_cat_entries;
1049 if( $copy->isdeleted ) {
1050 $evt = delete_copy($editor, $override, $vol, $copy);
1051 return $evt if $evt;
1053 } elsif( $copy->isnew ) {
1054 $evt = create_copy( $editor, $vol, $copy );
1055 return $evt if $evt;
1057 } elsif( $copy->ischanged ) {
1059 $evt = update_copy( $editor, $override, $vol, $copy );
1060 return $evt if $evt;
1063 $copy->stat_cat_entries( $sc_entries );
1064 $evt = update_copy_stat_entries($editor, $copy, $delete_stats);
1065 return $evt if $evt;
1068 $logger->debug("vol-update: done updating copy batch");
1073 sub fix_copy_price {
1076 if(defined $copy->price) {
1077 my $p = $copy->price || 0;
1082 my $d = $copy->deposit_amount || 0;
1084 $copy->deposit_amount($d);
1089 my( $editor, $override, $vol, $copy ) = @_;
1092 my $org = (ref $copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
1093 return $evt if ( $evt = org_cannot_have_vols($editor, $org) );
1095 $logger->info("vol-update: updating copy ".$copy->id);
1096 my $orig_copy = $editor->retrieve_asset_copy($copy->id);
1097 my $orig_vol = $editor->retrieve_asset_call_number($copy->call_number);
1099 $copy->editor($editor->requestor->id);
1100 $copy->edit_date('now');
1102 $copy->age_protect( $copy->age_protect->id )
1103 if ref $copy->age_protect;
1105 fix_copy_price($copy);
1107 return $editor->event unless $editor->update_asset_copy($copy);
1108 return remove_empty_objects($editor, $override, $orig_vol);
1112 sub remove_empty_objects {
1113 my( $editor, $override, $vol ) = @_;
1115 my $koe = $U->ou_ancestor_setting_value(
1116 $editor->requestor->ws_ou, 'cat.bib.keep_on_empty', $editor);
1117 my $aoe = $U->ou_ancestor_setting_value(
1118 $editor->requestor->ws_ou, 'cat.bib.alert_on_empty', $editor);
1120 if( title_is_empty($editor, $vol->record, $vol->id) ) {
1122 # delete this volume if it's not already marked as deleted
1123 unless( $U->is_true($vol->deleted) || $vol->isdeleted ) {
1125 $vol->editor($editor->requestor->id);
1126 $vol->edit_date('now');
1127 $editor->update_asset_call_number($vol) or return $editor->event;
1131 # delete the bib record if the keep-on-empty setting is not set
1132 my $evt = delete_rec($editor, $vol->record);
1133 return $evt if $evt;
1136 # return the empty alert if the alert-on-empty setting is set
1137 return OpenILS::Event->new('TITLE_LAST_COPY', payload => $vol->record ) if $aoe;
1144 __PACKAGE__->register_method (
1145 method => 'delete_bib_record',
1146 api_name => 'open-ils.cat.biblio.record_entry.delete');
1148 sub delete_bib_record {
1149 my($self, $conn, $auth, $rec_id) = @_;
1150 my $e = new_editor(xact=>1, authtoken=>$auth);
1151 return $e->die_event unless $e->checkauth;
1152 return $e->die_event unless $e->allowed('DELETE_RECORD', $e->requestor->ws_ou);
1153 my $vols = $e->search_asset_call_number({record=>$rec_id, deleted=>'f'});
1154 return OpenILS::Event->new('RECORD_NOT_EMPTY', payload=>$rec_id) if @$vols;
1155 my $evt = delete_rec($e, $rec_id);
1156 if($evt) { $e->rollback; return $evt; }
1162 # marks a record as deleted
1164 my( $editor, $rec_id ) = @_;
1166 my $rec = $editor->retrieve_biblio_record_entry($rec_id)
1167 or return $editor->event;
1169 return undef if $U->is_true($rec->deleted);
1173 $rec->editor( $editor->requestor->id );
1174 $rec->edit_date('now');
1175 $editor->update_biblio_record_entry($rec) or return $editor->event;
1182 my( $editor, $override, $vol, $copy ) = @_;
1184 return $editor->event unless
1185 $editor->allowed('DELETE_COPY',copy_perm_org($vol, $copy));
1187 my $stat = $U->copy_status($copy->status)->id;
1190 return OpenILS::Event->new('COPY_DELETE_WARNING', payload => $copy->id )
1191 if $stat == OILS_COPY_STATUS_CHECKED_OUT or
1192 $stat == OILS_COPY_STATUS_IN_TRANSIT or
1193 $stat == OILS_COPY_STATUS_ON_HOLDS_SHELF or
1194 $stat == OILS_COPY_STATUS_ILL;
1197 $logger->info("vol-update: deleting copy ".$copy->id);
1198 $copy->deleted('t');
1200 $copy->editor($editor->requestor->id);
1201 $copy->edit_date('now');
1202 $editor->update_asset_copy($copy) or return $editor->event;
1204 # Delete any open transits for this copy
1205 my $transits = $editor->search_action_transit_copy(
1206 { target_copy=>$copy->id, dest_recv_time => undef } );
1208 for my $t (@$transits) {
1209 $editor->delete_action_transit_copy($t)
1210 or return $editor->event;
1213 return remove_empty_objects($editor, $override, $vol);
1218 my( $editor, $vol, $copy ) = @_;
1220 my $existing = $editor->search_asset_copy(
1221 { barcode => $copy->barcode, deleted => 'f' } );
1223 return OpenILS::Event->new('ITEM_BARCODE_EXISTS') if @$existing;
1225 # see if the volume this copy references is marked as deleted
1226 my $evol = $editor->retrieve_asset_call_number($copy->call_number)
1227 or return $editor->event;
1228 return OpenILS::Event->new('VOLUME_DELETED', vol => $evol->id)
1229 if $U->is_true($evol->deleted);
1232 my $org = (ref $copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
1233 return $evt if ( $evt = org_cannot_have_vols($editor, $org) );
1236 $copy->creator($editor->requestor->id);
1237 $copy->create_date('now');
1238 fix_copy_price($copy);
1240 $editor->create_asset_copy($copy) or return $editor->event;
1244 # if 'delete_stats' is true, the copy->stat_cat_entries data is
1245 # treated as the authoritative list for the copy. existing entries
1246 # that are not in said list will be deleted from the DB
1247 sub update_copy_stat_entries {
1248 my( $editor, $copy, $delete_stats ) = @_;
1250 return undef if $copy->isdeleted;
1251 return undef unless $copy->ischanged or $copy->isnew;
1254 my $entries = $copy->stat_cat_entries;
1256 if( $delete_stats ) {
1257 $entries = ($entries and @$entries) ? $entries : [];
1259 return undef unless ($entries and @$entries);
1262 my $maps = $editor->search_asset_stat_cat_entry_copy_map({owning_copy=>$copy->id});
1265 # if there is no stat cat entry on the copy who's id matches the
1266 # current map's id, remove the map from the database
1267 for my $map (@$maps) {
1268 if(! grep { $_->id == $map->stat_cat_entry } @$entries ) {
1270 $logger->info("copy update found stale ".
1271 "stat cat entry map ".$map->id. " on copy ".$copy->id);
1273 $editor->delete_asset_stat_cat_entry_copy_map($map)
1274 or return $editor->event;
1279 # go through the stat cat update/create process
1280 for my $entry (@$entries) {
1283 # if this link already exists in the DB, don't attempt to re-create it
1284 next if( grep{$_->stat_cat_entry == $entry->id} @$maps );
1286 my $new_map = Fieldmapper::asset::stat_cat_entry_copy_map->new();
1288 my $sc = ref($entry->stat_cat) ? $entry->stat_cat->id : $entry->stat_cat;
1290 $new_map->stat_cat( $sc );
1291 $new_map->stat_cat_entry( $entry->id );
1292 $new_map->owning_copy( $copy->id );
1294 $editor->create_asset_stat_cat_entry_copy_map($new_map)
1295 or return $editor->event;
1297 $logger->info("copy update created new stat cat entry map ".$editor->data);
1305 my( $override, $editor, $vol ) = @_;
1308 return $evt if ( $evt = org_cannot_have_vols($editor, $vol->owning_lib) );
1310 # see if the record this volume references is marked as deleted
1311 my $rec = $editor->retrieve_biblio_record_entry($vol->record)
1312 or return $editor->event;
1313 return OpenILS::Event->new('BIB_RECORD_DELETED', rec => $rec->id)
1314 if $U->is_true($rec->deleted);
1316 # first lets see if there are any collisions
1317 my $vols = $editor->search_asset_call_number( {
1318 owning_lib => $vol->owning_lib,
1319 record => $vol->record,
1320 label => $vol->label,
1327 # we've found an exising volume
1329 $label = $vol->label;
1331 return OpenILS::Event->new(
1332 'VOLUME_LABEL_EXISTS', payload => $vol->id);
1336 # create a temp label so we can create the new volume,
1337 # then de-dup it with the existing volume
1338 $vol->label( "__SYSTEM_TMP_$$".time) if $label;
1340 $vol->creator($editor->requestor->id);
1341 $vol->create_date('now');
1342 $vol->editor($editor->requestor->id);
1343 $vol->edit_date('now');
1346 $editor->create_asset_call_number($vol) or return $editor->event;
1349 # now restore the label and merge into the existing record
1350 $vol->label($label);
1352 OpenILS::Application::Cat::Merge::merge_volumes($editor, [$vol], $$vols[0]);
1353 return $evt if $evt;
1360 __PACKAGE__->register_method (
1361 method => 'batch_volume_transfer',
1362 api_name => 'open-ils.cat.asset.volume.batch.transfer',
1365 __PACKAGE__->register_method (
1366 method => 'batch_volume_transfer',
1367 api_name => 'open-ils.cat.asset.volume.batch.transfer.override',
1371 sub batch_volume_transfer {
1372 my( $self, $conn, $auth, $args ) = @_;
1375 my $rec = $$args{docid};
1376 my $o_lib = $$args{lib};
1377 my $vol_ids = $$args{volumes};
1379 my $override = 1 if $self->api_name =~ /override/;
1381 $logger->info("merge: transferring volumes to lib=$o_lib and record=$rec");
1383 my $e = new_editor(authtoken => $auth, xact =>1);
1384 return $e->event unless $e->checkauth;
1385 return $e->event unless $e->allowed('UPDATE_VOLUME', $o_lib);
1387 my $dorg = $e->retrieve_actor_org_unit($o_lib)
1388 or return $e->event;
1390 my $ou_type = $e->retrieve_actor_org_unit_type($dorg->ou_type)
1391 or return $e->event;
1393 return $evt if ( $evt = org_cannot_have_vols($e, $o_lib) );
1395 my $vols = $e->batch_retrieve_asset_call_number($vol_ids);
1400 for my $vol (@$vols) {
1402 # if we've already looked at this volume, go to the next
1403 next if !$vol or grep { $vol->id == $_ } @seen;
1405 # grab all of the volumes in the list that have
1406 # the same label so they can be merged
1407 my @all = grep { $_->label eq $vol->label } @$vols;
1409 # take note of the fact that we've looked at this set of volumes
1410 push( @seen, $_->id ) for @all;
1411 push( @rec_ids, $_->record ) for @all;
1413 # for each volume, see if there are any copies that have a
1414 # remote circ_lib (circ_lib != vol->owning_lib and != $o_lib ).
1416 unless( $override ) {
1419 $logger->debug("merge: searching for copies with remote circ_lib for volume ".$v->id);
1421 call_number => $v->id,
1422 circ_lib => { "not in" => [ $o_lib, $v->owning_lib ] },
1426 my $copies = $e->search_asset_copy($args, {idlist=>1});
1428 # if the copy's circ_lib matches the destination lib,
1430 return OpenILS::Event->new('COPY_REMOTE_CIRC_LIB') if @$copies;
1434 # see if there is a volume at the destination lib that
1435 # already has the requested label
1436 my $existing_vol = $e->search_asset_call_number(
1438 label => $vol->label,
1440 owning_lib =>$o_lib,
1445 if( $existing_vol ) {
1447 if( grep { $_->id == $existing_vol->id } @all ) {
1448 # this volume is already accounted for in our list of volumes to merge
1449 $existing_vol = undef;
1452 # this volume exists on the destination record/owning_lib and must
1453 # be used as the destination for merging
1454 $logger->debug("merge: volume already exists at destination record: ".
1455 $existing_vol->id.' : '.$existing_vol->label) if $existing_vol;
1459 if( @all > 1 || $existing_vol ) {
1460 $logger->info("merge: found collisions in volume transfer");
1461 my @args = ($e, \@all);
1462 @args = ($e, \@all, $existing_vol) if $existing_vol;
1463 ($vol, $evt) = OpenILS::Application::Cat::Merge::merge_volumes(@args);
1464 return $evt if $evt;
1467 if( !$existing_vol ) {
1469 $vol->owning_lib($o_lib);
1471 $vol->editor($e->requestor->id);
1472 $vol->edit_date('now');
1474 $logger->info("merge: updating volume ".$vol->id);
1475 $e->update_asset_call_number($vol) or return $e->event;
1478 $logger->info("merge: bypassing volume update because existing volume used as target");
1481 # regardless of what volume was used as the destination,
1482 # update any copies that have moved over to the new lib
1483 my $copies = $e->search_asset_copy({call_number=>$vol->id, deleted => 'f'});
1485 # update circ lib on the copies - make this a method flag?
1486 for my $copy (@$copies) {
1487 next if $copy->circ_lib == $o_lib;
1488 $logger->info("merge: transfer moving circ lib on copy ".$copy->id);
1489 $copy->circ_lib($o_lib);
1490 $copy->editor($e->requestor->id);
1491 $copy->edit_date('now');
1492 $e->update_asset_copy($copy) or return $e->event;
1495 # Now see if any empty records need to be deleted after all of this
1498 $logger->debug("merge: seeing if we should delete record $_...");
1499 $evt = delete_rec($e, $_) if title_is_empty($e, $_);
1500 return $evt if $evt;
1504 # $evt = remove_empty_objects($e, $override, $_);
1508 $logger->info("merge: transfer succeeded");
1515 sub org_cannot_have_vols {
1519 my $org = $e->retrieve_actor_org_unit($org_id)
1520 or return $e->event;
1522 my $ou_type = $e->retrieve_actor_org_unit_type($org->ou_type)
1523 or return $e->event;
1525 return OpenILS::Event->new('ORG_CANNOT_HAVE_VOLS')
1526 unless $U->is_true($ou_type->can_have_vols);
1534 __PACKAGE__->register_method(
1535 api_name => 'open-ils.cat.call_number.find_or_create',
1536 method => 'find_or_create_volume',
1539 sub find_or_create_volume {
1540 my( $self, $conn, $auth, $label, $record_id, $org_id ) = @_;
1541 my $e = new_editor(authtoken=>$auth, xact=>1);
1542 return $e->die_event unless $e->checkauth;
1546 if($record_id == OILS_PRECAT_RECORD) {
1548 $vol = $e->retrieve_asset_call_number(OILS_PRECAT_CALL_NUMBER)
1549 or return $e->die_event;
1553 $vol = $e->search_asset_call_number(
1554 {label => $label, record => $record_id, owning_lib => $org_id, deleted => 'f'},
1559 # If the volume exists, return the ID
1560 if( $vol ) { $e->rollback; return $vol; }
1562 # -----------------------------------------------------------------
1563 # Otherwise, create a new volume with the given attributes
1564 # -----------------------------------------------------------------
1566 return $e->die_event unless $e->allowed('UPDATE_VOLUME', $org_id);
1568 $vol = Fieldmapper::asset::call_number->new;
1569 $vol->owning_lib($org_id);
1570 $vol->label($label);
1571 $vol->record($record_id);
1573 my $evt = create_volume( 0, $e, $vol );
1574 return $evt if $evt;