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 # ---------------------------------------------------------------------------
885 # returns true if the given title (id) has no un-deleted
888 my( $editor, $rid ) = @_;
890 return 0 if $rid == OILS_PRECAT_RECORD;
892 my $cnlist = $editor->search_asset_call_number(
893 { record => $rid, deleted => 'f' }, { idlist => 1 } );
894 return 1 unless @$cnlist;
896 for my $cn (@$cnlist) {
897 my $copylist = $editor->search_asset_copy(
899 { call_number => $cn, deleted => 'f' },
902 return 0 if @$copylist; # false if we find any copies
909 __PACKAGE__->register_method(
910 method => "fleshed_volume_update",
911 api_name => "open-ils.cat.asset.volume.fleshed.batch.update",);
913 __PACKAGE__->register_method(
914 method => "fleshed_volume_update",
915 api_name => "open-ils.cat.asset.volume.fleshed.batch.update.override",);
917 sub fleshed_volume_update {
918 my( $self, $conn, $auth, $volumes, $delete_stats ) = @_;
919 my( $reqr, $evt ) = $U->checkses($auth);
922 my $override = ($self->api_name =~ /override/);
923 my $editor = new_editor( requestor => $reqr, xact => 1 );
925 for my $vol (@$volumes) {
926 $logger->info("vol-update: investigating volume ".$vol->id);
928 $vol->editor($reqr->id);
929 $vol->edit_date('now');
931 my $copies = $vol->copies;
934 $vol->editor($editor->requestor->id);
935 $vol->edit_date('now');
937 if( $vol->isdeleted ) {
939 $logger->info("vol-update: deleting volume");
940 my $cs = $editor->search_asset_copy(
941 { call_number => $vol->id, deleted => 'f' } );
942 return OpenILS::Event->new(
943 'VOLUME_NOT_EMPTY', payload => $vol->id ) if @$cs;
946 return $editor->event unless
947 $editor->update_asset_call_number($vol);
950 } elsif( $vol->isnew ) {
951 $logger->info("vol-update: creating volume");
952 $evt = create_volume( $override, $editor, $vol );
955 } elsif( $vol->ischanged ) {
956 $logger->info("vol-update: update volume");
957 $evt = update_volume($vol, $editor);
961 # now update any attached copies
962 if( $copies and @$copies and !$vol->isdeleted ) {
963 $_->call_number($vol->id) for @$copies;
964 $evt = update_fleshed_copies( $editor, $override, $vol, $copies, $delete_stats );
970 return scalar(@$volumes);
979 return $evt if ( $evt = org_cannot_have_vols($editor, $vol->owning_lib) );
981 my $vols = $editor->search_asset_call_number( {
982 owning_lib => $vol->owning_lib,
983 record => $vol->record,
984 label => $vol->label,
989 # There exists a different volume in the DB with the same properties
990 return OpenILS::Event->new('VOLUME_LABEL_EXISTS', payload => $vol->id)
991 if grep { $_->id ne $vol->id } @$vols;
993 return $editor->event unless $editor->update_asset_call_number($vol);
1000 my( $vol, $copy ) = @_;
1001 my $org = $vol->owning_lib;
1002 if( $vol->id == OILS_PRECAT_CALL_NUMBER ) {
1003 $org = ref($copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
1005 $logger->debug("using copy perm org $org");
1010 # this does the actual work
1011 sub update_fleshed_copies {
1012 my( $editor, $override, $vol, $copies, $delete_stats ) = @_;
1015 my $fetchvol = ($vol) ? 0 : 1;
1018 $cache{$vol->id} = $vol if $vol;
1020 for my $copy (@$copies) {
1022 my $copyid = $copy->id;
1023 $logger->info("vol-update: inspecting copy $copyid");
1025 if( !($vol = $cache{$copy->call_number}) ) {
1026 $vol = $cache{$copy->call_number} =
1027 $editor->retrieve_asset_call_number($copy->call_number);
1028 return $editor->event unless $vol;
1031 return $editor->event unless
1032 $editor->allowed('UPDATE_COPY', copy_perm_org($vol, $copy));
1034 $copy->editor($editor->requestor->id);
1035 $copy->edit_date('now');
1037 $copy->status( $copy->status->id ) if ref($copy->status);
1038 $copy->location( $copy->location->id ) if ref($copy->location);
1039 $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
1041 my $sc_entries = $copy->stat_cat_entries;
1042 $copy->clear_stat_cat_entries;
1044 if( $copy->isdeleted ) {
1045 $evt = delete_copy($editor, $override, $vol, $copy);
1046 return $evt if $evt;
1048 } elsif( $copy->isnew ) {
1049 $evt = create_copy( $editor, $vol, $copy );
1050 return $evt if $evt;
1052 } elsif( $copy->ischanged ) {
1054 $evt = update_copy( $editor, $override, $vol, $copy );
1055 return $evt if $evt;
1058 $copy->stat_cat_entries( $sc_entries );
1059 $evt = update_copy_stat_entries($editor, $copy, $delete_stats);
1060 return $evt if $evt;
1063 $logger->debug("vol-update: done updating copy batch");
1068 sub fix_copy_price {
1071 if(defined $copy->price) {
1072 my $p = $copy->price || 0;
1077 my $d = $copy->deposit_amount || 0;
1079 $copy->deposit_amount($d);
1084 my( $editor, $override, $vol, $copy ) = @_;
1087 my $org = (ref $copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
1088 return $evt if ( $evt = org_cannot_have_vols($editor, $org) );
1090 $logger->info("vol-update: updating copy ".$copy->id);
1091 my $orig_copy = $editor->retrieve_asset_copy($copy->id);
1092 my $orig_vol = $editor->retrieve_asset_call_number($copy->call_number);
1094 $copy->editor($editor->requestor->id);
1095 $copy->edit_date('now');
1097 $copy->age_protect( $copy->age_protect->id )
1098 if ref $copy->age_protect;
1100 fix_copy_price($copy);
1102 return $editor->event unless $editor->update_asset_copy($copy);
1103 return remove_empty_objects($editor, $override, $orig_vol);
1107 sub remove_empty_objects {
1108 my( $editor, $override, $vol ) = @_;
1110 my $koe = $U->ou_ancestor_setting_value(
1111 $editor->requestor->ws_ou, 'cat.bib.keep_on_empty', $editor);
1112 my $aoe = $U->ou_ancestor_setting_value(
1113 $editor->requestor->ws_ou, 'cat.bib.alert_on_empty', $editor);
1115 if( title_is_empty($editor, $vol->record) ) {
1117 # delete this volume if it's not already marked as deleted
1118 unless( $U->is_true($vol->deleted) || $vol->isdeleted ) {
1120 $vol->editor($editor->requestor->id);
1121 $vol->edit_date('now');
1122 $editor->update_asset_call_number($vol) or return $editor->event;
1126 # delete the bib record if the keep-on-empty setting is not set
1127 my $evt = delete_rec($editor, $vol->record);
1128 return $evt if $evt;
1131 # return the empty alert if the alert-on-empty setting is set
1132 return OpenILS::Event->new('TITLE_LAST_COPY', payload => $vol->record ) if $aoe;
1139 __PACKAGE__->register_method (
1140 method => 'delete_bib_record',
1141 api_name => 'open-ils.cat.biblio.record_entry.delete');
1143 sub delete_bib_record {
1144 my($self, $conn, $auth, $rec_id) = @_;
1145 my $e = new_editor(xact=>1, authtoken=>$auth);
1146 return $e->die_event unless $e->checkauth;
1147 return $e->die_event unless $e->allowed('DELETE_RECORD', $e->requestor->ws_ou);
1148 my $vols = $e->search_asset_call_number({record=>$rec_id, deleted=>'f'});
1149 return OpenILS::Event->new('RECORD_NOT_EMPTY', payload=>$rec_id) if @$vols;
1150 my $evt = delete_rec($e, $rec_id);
1151 if($evt) { $e->rollback; return $evt; }
1157 # marks a record as deleted
1159 my( $editor, $rec_id ) = @_;
1161 my $rec = $editor->retrieve_biblio_record_entry($rec_id)
1162 or return $editor->event;
1164 return undef if $U->is_true($rec->deleted);
1168 $rec->editor( $editor->requestor->id );
1169 $rec->edit_date('now');
1170 $editor->update_biblio_record_entry($rec) or return $editor->event;
1177 my( $editor, $override, $vol, $copy ) = @_;
1179 return $editor->event unless
1180 $editor->allowed('DELETE_COPY',copy_perm_org($vol, $copy));
1182 my $stat = $U->copy_status($copy->status)->id;
1185 return OpenILS::Event->new('COPY_DELETE_WARNING', payload => $copy->id )
1186 if $stat == OILS_COPY_STATUS_CHECKED_OUT or
1187 $stat == OILS_COPY_STATUS_IN_TRANSIT or
1188 $stat == OILS_COPY_STATUS_ON_HOLDS_SHELF or
1189 $stat == OILS_COPY_STATUS_ILL;
1192 $logger->info("vol-update: deleting copy ".$copy->id);
1193 $copy->deleted('t');
1195 $copy->editor($editor->requestor->id);
1196 $copy->edit_date('now');
1197 $editor->update_asset_copy($copy) or return $editor->event;
1199 # Delete any open transits for this copy
1200 my $transits = $editor->search_action_transit_copy(
1201 { target_copy=>$copy->id, dest_recv_time => undef } );
1203 for my $t (@$transits) {
1204 $editor->delete_action_transit_copy($t)
1205 or return $editor->event;
1208 return remove_empty_objects($editor, $override, $vol);
1213 my( $editor, $vol, $copy ) = @_;
1215 my $existing = $editor->search_asset_copy(
1216 { barcode => $copy->barcode, deleted => 'f' } );
1218 return OpenILS::Event->new('ITEM_BARCODE_EXISTS') if @$existing;
1220 # see if the volume this copy references is marked as deleted
1221 my $evol = $editor->retrieve_asset_call_number($copy->call_number)
1222 or return $editor->event;
1223 return OpenILS::Event->new('VOLUME_DELETED', vol => $evol->id)
1224 if $U->is_true($evol->deleted);
1227 my $org = (ref $copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
1228 return $evt if ( $evt = org_cannot_have_vols($editor, $org) );
1231 $copy->creator($editor->requestor->id);
1232 $copy->create_date('now');
1233 fix_copy_price($copy);
1235 $editor->create_asset_copy($copy) or return $editor->event;
1239 # if 'delete_stats' is true, the copy->stat_cat_entries data is
1240 # treated as the authoritative list for the copy. existing entries
1241 # that are not in said list will be deleted from the DB
1242 sub update_copy_stat_entries {
1243 my( $editor, $copy, $delete_stats ) = @_;
1245 return undef if $copy->isdeleted;
1246 return undef unless $copy->ischanged or $copy->isnew;
1249 my $entries = $copy->stat_cat_entries;
1251 if( $delete_stats ) {
1252 $entries = ($entries and @$entries) ? $entries : [];
1254 return undef unless ($entries and @$entries);
1257 my $maps = $editor->search_asset_stat_cat_entry_copy_map({owning_copy=>$copy->id});
1260 # if there is no stat cat entry on the copy who's id matches the
1261 # current map's id, remove the map from the database
1262 for my $map (@$maps) {
1263 if(! grep { $_->id == $map->stat_cat_entry } @$entries ) {
1265 $logger->info("copy update found stale ".
1266 "stat cat entry map ".$map->id. " on copy ".$copy->id);
1268 $editor->delete_asset_stat_cat_entry_copy_map($map)
1269 or return $editor->event;
1274 # go through the stat cat update/create process
1275 for my $entry (@$entries) {
1278 # if this link already exists in the DB, don't attempt to re-create it
1279 next if( grep{$_->stat_cat_entry == $entry->id} @$maps );
1281 my $new_map = Fieldmapper::asset::stat_cat_entry_copy_map->new();
1283 my $sc = ref($entry->stat_cat) ? $entry->stat_cat->id : $entry->stat_cat;
1285 $new_map->stat_cat( $sc );
1286 $new_map->stat_cat_entry( $entry->id );
1287 $new_map->owning_copy( $copy->id );
1289 $editor->create_asset_stat_cat_entry_copy_map($new_map)
1290 or return $editor->event;
1292 $logger->info("copy update created new stat cat entry map ".$editor->data);
1300 my( $override, $editor, $vol ) = @_;
1303 return $evt if ( $evt = org_cannot_have_vols($editor, $vol->owning_lib) );
1305 # see if the record this volume references is marked as deleted
1306 my $rec = $editor->retrieve_biblio_record_entry($vol->record)
1307 or return $editor->event;
1308 return OpenILS::Event->new('BIB_RECORD_DELETED', rec => $rec->id)
1309 if $U->is_true($rec->deleted);
1311 # first lets see if there are any collisions
1312 my $vols = $editor->search_asset_call_number( {
1313 owning_lib => $vol->owning_lib,
1314 record => $vol->record,
1315 label => $vol->label,
1322 # we've found an exising volume
1324 $label = $vol->label;
1326 return OpenILS::Event->new(
1327 'VOLUME_LABEL_EXISTS', payload => $vol->id);
1331 # create a temp label so we can create the new volume,
1332 # then de-dup it with the existing volume
1333 $vol->label( "__SYSTEM_TMP_$$".time) if $label;
1335 $vol->creator($editor->requestor->id);
1336 $vol->create_date('now');
1337 $vol->editor($editor->requestor->id);
1338 $vol->edit_date('now');
1341 $editor->create_asset_call_number($vol) or return $editor->event;
1344 # now restore the label and merge into the existing record
1345 $vol->label($label);
1347 OpenILS::Application::Cat::Merge::merge_volumes($editor, [$vol], $$vols[0]);
1348 return $evt if $evt;
1355 __PACKAGE__->register_method (
1356 method => 'batch_volume_transfer',
1357 api_name => 'open-ils.cat.asset.volume.batch.transfer',
1360 __PACKAGE__->register_method (
1361 method => 'batch_volume_transfer',
1362 api_name => 'open-ils.cat.asset.volume.batch.transfer.override',
1366 sub batch_volume_transfer {
1367 my( $self, $conn, $auth, $args ) = @_;
1370 my $rec = $$args{docid};
1371 my $o_lib = $$args{lib};
1372 my $vol_ids = $$args{volumes};
1374 my $override = 1 if $self->api_name =~ /override/;
1376 $logger->info("merge: transferring volumes to lib=$o_lib and record=$rec");
1378 my $e = new_editor(authtoken => $auth, xact =>1);
1379 return $e->event unless $e->checkauth;
1380 return $e->event unless $e->allowed('UPDATE_VOLUME', $o_lib);
1382 my $dorg = $e->retrieve_actor_org_unit($o_lib)
1383 or return $e->event;
1385 my $ou_type = $e->retrieve_actor_org_unit_type($dorg->ou_type)
1386 or return $e->event;
1388 return $evt if ( $evt = org_cannot_have_vols($e, $o_lib) );
1390 my $vols = $e->batch_retrieve_asset_call_number($vol_ids);
1395 for my $vol (@$vols) {
1397 # if we've already looked at this volume, go to the next
1398 next if !$vol or grep { $vol->id == $_ } @seen;
1400 # grab all of the volumes in the list that have
1401 # the same label so they can be merged
1402 my @all = grep { $_->label eq $vol->label } @$vols;
1404 # take note of the fact that we've looked at this set of volumes
1405 push( @seen, $_->id ) for @all;
1406 push( @rec_ids, $_->record ) for @all;
1408 # for each volume, see if there are any copies that have a
1409 # remote circ_lib (circ_lib != vol->owning_lib and != $o_lib ).
1411 unless( $override ) {
1414 $logger->debug("merge: searching for copies with remote circ_lib for volume ".$v->id);
1416 call_number => $v->id,
1417 circ_lib => { "not in" => [ $o_lib, $v->owning_lib ] },
1421 my $copies = $e->search_asset_copy($args, {idlist=>1});
1423 # if the copy's circ_lib matches the destination lib,
1425 return OpenILS::Event->new('COPY_REMOTE_CIRC_LIB') if @$copies;
1429 # see if there is a volume at the destination lib that
1430 # already has the requested label
1431 my $existing_vol = $e->search_asset_call_number(
1433 label => $vol->label,
1435 owning_lib =>$o_lib,
1440 if( $existing_vol ) {
1442 if( grep { $_->id == $existing_vol->id } @all ) {
1443 # this volume is already accounted for in our list of volumes to merge
1444 $existing_vol = undef;
1447 # this volume exists on the destination record/owning_lib and must
1448 # be used as the destination for merging
1449 $logger->debug("merge: volume already exists at destination record: ".
1450 $existing_vol->id.' : '.$existing_vol->label) if $existing_vol;
1454 if( @all > 1 || $existing_vol ) {
1455 $logger->info("merge: found collisions in volume transfer");
1456 my @args = ($e, \@all);
1457 @args = ($e, \@all, $existing_vol) if $existing_vol;
1458 ($vol, $evt) = OpenILS::Application::Cat::Merge::merge_volumes(@args);
1459 return $evt if $evt;
1462 if( !$existing_vol ) {
1464 $vol->owning_lib($o_lib);
1466 $vol->editor($e->requestor->id);
1467 $vol->edit_date('now');
1469 $logger->info("merge: updating volume ".$vol->id);
1470 $e->update_asset_call_number($vol) or return $e->event;
1473 $logger->info("merge: bypassing volume update because existing volume used as target");
1476 # regardless of what volume was used as the destination,
1477 # update any copies that have moved over to the new lib
1478 my $copies = $e->search_asset_copy({call_number=>$vol->id, deleted => 'f'});
1480 # update circ lib on the copies - make this a method flag?
1481 for my $copy (@$copies) {
1482 next if $copy->circ_lib == $o_lib;
1483 $logger->info("merge: transfer moving circ lib on copy ".$copy->id);
1484 $copy->circ_lib($o_lib);
1485 $copy->editor($e->requestor->id);
1486 $copy->edit_date('now');
1487 $e->update_asset_copy($copy) or return $e->event;
1490 # Now see if any empty records need to be deleted after all of this
1493 $logger->debug("merge: seeing if we should delete record $_...");
1494 $evt = delete_rec($e, $_) if title_is_empty($e, $_);
1495 return $evt if $evt;
1499 # $evt = remove_empty_objects($e, $override, $_);
1503 $logger->info("merge: transfer succeeded");
1510 sub org_cannot_have_vols {
1514 my $org = $e->retrieve_actor_org_unit($org_id)
1515 or return $e->event;
1517 my $ou_type = $e->retrieve_actor_org_unit_type($org->ou_type)
1518 or return $e->event;
1520 return OpenILS::Event->new('ORG_CANNOT_HAVE_VOLS')
1521 unless $U->is_true($ou_type->can_have_vols);
1529 __PACKAGE__->register_method(
1530 api_name => 'open-ils.cat.call_number.find_or_create',
1531 method => 'find_or_create_volume',
1534 sub find_or_create_volume {
1535 my( $self, $conn, $auth, $label, $record_id, $org_id ) = @_;
1536 my $e = new_editor(authtoken=>$auth, xact=>1);
1537 return $e->die_event unless $e->checkauth;
1541 if($record_id == OILS_PRECAT_RECORD) {
1543 $vol = $e->retrieve_asset_call_number(OILS_PRECAT_CALL_NUMBER)
1544 or return $e->die_event;
1548 $vol = $e->search_asset_call_number(
1549 {label => $label, record => $record_id, owning_lib => $org_id, deleted => 'f'},
1554 # If the volume exists, return the ID
1555 if( $vol ) { $e->rollback; return $vol; }
1557 # -----------------------------------------------------------------
1558 # Otherwise, create a new volume with the given attributes
1559 # -----------------------------------------------------------------
1561 return $e->die_event unless $e->allowed('UPDATE_VOLUME', $org_id);
1563 $vol = Fieldmapper::asset::call_number->new;
1564 $vol->owning_lib($org_id);
1565 $vol->label($label);
1566 $vol->record($record_id);
1568 my $evt = create_volume( 0, $e, $vol );
1569 return $evt if $evt;