]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Cat/BibCommon.pm
LP2061136 - Stamping 1405 DB upgrade script
[Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / Application / Cat / BibCommon.pm
1 package OpenILS::Application::Cat::BibCommon;
2 use strict; use warnings;
3 use OpenILS::Utils::CStoreEditor q/:funcs/;
4 use OpenSRF::Utils::Logger qw($logger);
5 use OpenILS::Application::AppUtils;
6 use OpenILS::Utils::Fieldmapper;
7 use OpenILS::Const qw/:const/;
8 use OpenSRF::AppSession;
9 use OpenILS::Event;
10 my $U = 'OpenILS::Application::AppUtils';
11
12
13 # ---------------------------------------------------------------------------
14 # Shared bib mangling code.  Do not publish methods from here.
15 # ---------------------------------------------------------------------------
16
17 my $__bib_sources;
18 sub bib_source_from_name {
19     my $name = shift;
20     $logger->debug("searching for bib source: $name");
21
22     fetch_bib_sources();
23
24     my ($s) = grep { lc($_->source) eq lc($name) } @$__bib_sources;
25
26     return $s->id if $s;
27     return undef;
28 }
29
30 sub fetch_bib_sources {
31     $__bib_sources = new_editor()->retrieve_all_config_bib_source()
32         unless $__bib_sources;
33     return $__bib_sources;
34 }
35
36
37 sub biblio_record_replace_marc  {
38     my($class, $e, $recid, $newxml, $source, $fixtcn, $override, $strip_grps) = @_;
39
40     $override = { all => 1 } if($override && !ref $override);
41     $override = { all => 0 } if(!ref $override);
42
43     my $rec = $e->retrieve_biblio_record_entry($recid)
44         or return $e->die_event;
45
46     # See if there is a different record in the database that has our TCN value
47     # If we're not updating the TCN, all we care about it the marcdoc
48     # XXX should .update even bother with the tcn_info if it's not going to replace it?
49     # there is the potential for returning a TCN_EXISTS event, even though no replacement happens
50
51     my( $tcn, $tsource, $marcdoc, $evt);
52
53     if($fixtcn or $override->{all} or $override->{events}) {
54
55         ($tcn, $tsource, $marcdoc, $evt) = 
56             _find_tcn_info($e, $newxml, $override, $recid);
57
58         return $evt if $evt;
59
60         $rec->tcn_value($tcn) if ($tcn);
61         $rec->tcn_source($tsource);
62
63     } else {
64
65         $marcdoc = __make_marc_doc($newxml);
66     }
67
68     my $marc = $U->strip_marc_fields($e, $marcdoc, $strip_grps);
69
70     $rec->source(bib_source_from_name($source)) if $source;
71     $rec->editor($e->requestor->id);
72     $rec->edit_date('now');
73     $rec->marc($marc);
74     $e->update_biblio_record_entry($rec) or return $e->die_event;
75
76     return $rec;
77 }
78
79 sub biblio_record_xml_import {
80     my($class, $e, $xml, $source, $auto_tcn, $override, $strip_grps) = @_;
81
82     $override = { all => 1 } if($override && !ref $override);
83     $override = { all => 0 } if(!ref $override);
84
85     my( $evt, $tcn, $tcn_source, $marcdoc );
86
87     my $use_id = $e->retrieve_config_global_flag('cat.bib.use_id_for_tcn');
88     $use_id = ($use_id and $U->is_true($use_id->enabled));
89
90     if( $auto_tcn or $use_id ) {
91         # auto_tcn forces a blank TCN value so the DB will have to generate one for us
92         $marcdoc = __make_marc_doc($xml);
93     } else {
94         ( $tcn, $tcn_source, $marcdoc, $evt ) = _find_tcn_info($e, $xml, $override);
95         return $evt if $evt;
96     }
97
98     # Silence warnings when _find_tcn_info() fails
99     $tcn ||= '';
100     $tcn_source ||= '';
101     $logger->info("user ".$e->requestor->id.
102         " creating new biblio entry with tcn=$tcn and tcn_source $tcn_source");
103
104     my $marc = $U->strip_marc_fields($e, $marcdoc, $strip_grps);
105
106     my $record = Fieldmapper::biblio::record_entry->new;
107
108     $record->source(bib_source_from_name($source)) if $source;
109     $record->tcn_source($tcn_source) if $tcn_source;
110     $record->tcn_value($tcn) if ($tcn);
111     $record->creator($e->requestor->id);
112     $record->editor($e->requestor->id);
113     $record->create_date('now');
114     $record->edit_date('now');
115     $record->marc($marc);
116
117     $record = $e->create_biblio_record_entry($record) or return $e->die_event;
118
119     if($use_id) {
120         my $existing = $e->search_biblio_record_entry(
121             {   
122                 tcn_value => $record->id,
123                 deleted => 'f'
124             }, { 
125                 idlist => 1 
126             }
127         );
128
129         if(@$existing) {
130             # leave the auto-generated tcn_value in place
131             $logger->warn("Collision using internal ID as tcn_value for record " . $record->id);
132         } else {
133             $record->tcn_value($record->id);
134             $e->update_biblio_record_entry($record) or return $e->die_event;
135         }
136     }
137
138     $logger->info("marc create/import created new record ".$record->id);
139     return $record;
140 }
141
142 sub __make_marc_doc {
143     my $xml = shift;
144     my $marcxml = XML::LibXML->new->parse_string($xml);
145     $marcxml->documentElement->setNamespace(MARC_NAMESPACE, "marc", 1 );
146     $marcxml->documentElement->setNamespace(MARC_NAMESPACE);
147     __remove_empty_marc_nodes($marcxml);
148     return $marcxml;
149 }
150
151 # remove empty control fields, subfields, and variable data fields, which
152 # can creep in via less-than-correct imported MARC records or issues
153 # with templates
154 sub __remove_empty_marc_nodes {
155     my $marcxml = shift;
156
157     __remove_if_childless($_) foreach $marcxml->documentElement->getElementsByTagNameNS(MARC_NAMESPACE, 'controlfield');
158     __remove_if_childless($_) foreach $marcxml->documentElement->getElementsByTagNameNS(MARC_NAMESPACE, 'subfield');
159     __remove_if_childless($_) foreach $marcxml->documentElement->getElementsByTagNameNS(MARC_NAMESPACE, 'datafield');
160 }
161
162 sub __remove_if_childless {
163     my $node = shift;
164     my @children = $node->childNodes();
165     my $has_nonblank_children = 0;
166     # can do this more concisely by requiring XML::LibXML >= 1.70 and using nonBlankChildNodes()
167     foreach my $node ($node->childNodes()) {
168         if ($node->nodeType != XML::LibXML::XML_TEXT_NODE || $node->nodeValue !~ /^\s*$/) {
169             $has_nonblank_children = 1;
170             last;
171         }
172     }
173     $node->parentNode->removeChild($node) unless $has_nonblank_children;
174 }
175
176 sub _find_tcn_info { 
177     my $editor      = shift;
178     my $xml         = shift;
179     my $override    = shift;
180     my $existing_rec    = shift || 0;
181
182     $override = { all => 1 } if($override && !ref $override);
183     $override = { all => 0 } if(!ref $override);
184
185     # parse the XML
186     my $marcxml = __make_marc_doc($xml);
187
188     my $xpath = '//marc:controlfield[@tag="001"]';
189     my $tcn = $marcxml->documentElement->findvalue($xpath);
190     $logger->info("biblio import located 001 (tcn) value of $tcn");
191
192     $xpath = '//marc:controlfield[@tag="003"]';
193     my $tcn_source = $marcxml->documentElement->findvalue($xpath) || "System Local";
194
195     if(my $rec = _tcn_exists($editor, $tcn, $tcn_source, $existing_rec) ) {
196
197         my $origtcn = $tcn;
198         $tcn = find_free_tcn( $marcxml, $editor, $existing_rec );
199
200         # if we're overriding, try to find a different TCN to use
201         if( $override->{all} || grep { $_ eq 'TCN_EXISTS' } @{$override->{events}} ) {
202
203          # XXX Create ALLOW_ALT_TCN permission check support 
204
205             $logger->info("tcn value $tcn already exists, attempting to override");
206
207             if(!$tcn) {
208                 return ( 
209                     undef, 
210                     undef, 
211                     undef,
212                     OpenILS::Event->new(
213                         'OPEN_TCN_NOT_FOUND', 
214                             payload => $marcxml->toString())
215                     );
216             }
217
218         } else {
219
220             $logger->warn("tcn value $origtcn already exists in import/create");
221
222             # otherwise, return event
223             return ( 
224                 undef, 
225                 undef, 
226                 undef,
227                 OpenILS::Event->new( 
228                     'TCN_EXISTS', payload => { 
229                         dup_record  => $rec, 
230                         tcn         => $origtcn,
231                         new_tcn     => $tcn
232                         }
233                     )
234                 );
235         }
236     }
237
238     return ($tcn, $tcn_source, $marcxml);
239 }
240
241 sub find_free_tcn {
242
243     my $marcxml = shift;
244     my $editor = shift;
245     my $existing_rec = shift;
246
247     my $xpath = '//marc:datafield[@tag="901"]/marc:subfield[@code="a"]';
248     my ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
249
250     if (!$tcn) {
251         $xpath = '//marc:datafield[@tag="039"]/marc:subfield[@code="a"]';
252         ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
253     }
254
255     $xpath = '//marc:datafield[@tag="901"]/marc:subfield[@code="b"]';
256     my ($tcn_source) = $marcxml->documentElement->findvalue($xpath);
257     if (!$tcn_source) {
258         $xpath = '//marc:datafield[@tag="039"]/marc:subfield[@code="b"]';
259         $tcn_source = $marcxml->documentElement->findvalue($xpath) || "System Local";
260     }
261
262     if(_tcn_exists($editor, $tcn, $tcn_source, $existing_rec)) {
263         $tcn = undef;
264     }
265
266
267     if(!$tcn) {
268         $xpath = '//marc:datafield[@tag="020"]/marc:subfield[@code="a"]';
269         ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
270         $tcn_source = "ISBN";
271         if(_tcn_exists($editor, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
272     }
273
274     if(!$tcn) { 
275         $xpath = '//marc:datafield[@tag="022"]/marc:subfield[@code="a"]';
276         ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
277         $tcn_source = "ISSN";
278         if(_tcn_exists($editor, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
279     }
280
281     if(!$tcn) {
282         $xpath = '//marc:datafield[@tag="010"]';
283         ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
284         $tcn_source = "LCCN";
285         if(_tcn_exists($editor, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
286     }
287
288     if(!$tcn) {
289         $xpath = '//marc:datafield[@tag="035"]/marc:subfield[@code="a"]';
290         ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
291         $tcn_source = "System Legacy";
292         if(_tcn_exists($editor, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
293
294         if($tcn) {
295             $marcxml->documentElement->removeChild(
296                 $marcxml->documentElement->findnodes( '//marc:datafield[@tag="035"]' )
297             );
298         }
299     }
300
301     return undef unless $tcn;
302     return $tcn;
303 }
304
305
306
307 sub _tcn_exists {
308     my $editor = shift;
309     my $tcn = shift;
310     my $source = shift;
311     my $existing_rec = shift || 0;
312
313     if(!$tcn) {return 0;}
314
315     $logger->debug("tcn_exists search for tcn $tcn and source $source and id $existing_rec");
316
317     # XXX why does the source matter?
318 #   my $req = $session->request(      
319 #       { tcn_value => $tcn, tcn_source => $source, deleted => 'f' } );
320
321     my $recs = $editor->search_biblio_record_entry(
322         {tcn_value => $tcn, deleted => 'f', id => {'!=' => $existing_rec}}, {idlist =>1});
323
324     if(@$recs) {
325         $logger->debug("_tcn_exists is true for tcn : $tcn ($source)");
326         return $recs->[0];
327     }
328
329     $logger->debug("_tcn_exists is false for tcn : $tcn ($source)");
330     return 0;
331 }
332
333
334 sub delete_rec {
335    my($class, $editor, $rec_id ) = @_;
336
337    my $rec = $editor->retrieve_biblio_record_entry($rec_id)
338       or return $editor->event;
339
340    return undef if $U->is_true($rec->deleted);
341    
342    $rec->deleted('t');
343    $rec->active('f');
344    $rec->editor( $editor->requestor->id );
345    $rec->edit_date('now');
346
347    # Set the leader/05 to indicate that the record has been deleted
348    my $marc = $rec->marc();
349    $marc =~ s{(<leader>.{5}).}{$1d};
350    $rec->marc($marc);
351
352    $editor->update_biblio_record_entry($rec) or return $editor->event;
353
354     my $holds = $editor->search_action_hold_request({
355         target => $rec->id,
356         hold_type => 'T',
357         cancel_time => undef,
358         fulfillment_time => undef
359     });
360
361     for my $hold (@$holds) {
362
363         $hold->cancel_time('now');
364         $hold->cancel_cause(1); # un-targeted expiration.
365         $editor->update_action_hold_request($hold) or return $editor->die_event;
366
367         my $at_ses = OpenSRF::AppSession->create('open-ils.trigger');
368         $at_ses->request(
369             'open-ils.trigger.event.autocreate',
370             'hold_request.cancel.expire_no_target', 
371             $hold, $hold->pickup_lib);
372     }
373
374    return undef;
375 }
376
377
378 # ---------------------------------------------------------------------------
379 # returns true if the given title (id) has no un-deleted volumes or 
380 # copies attached.  If a context volume is defined, a record
381 # is considered empty only if the context volume is the only
382 # remaining volume on the record.  
383 # ---------------------------------------------------------------------------
384 sub title_is_empty {
385     my($class, $editor, $rid, $vol_id) = @_;
386
387     # check if $rid is an object, because may be passing the volume
388     # with a fleshed record in one of our callers.
389     $rid = $rid->id() if (ref($rid));
390
391     return 0 if $rid == OILS_PRECAT_RECORD;
392
393     my $cnlist = $editor->search_asset_call_number(
394         { record => $rid, deleted => 'f' }, { idlist => 1 } );
395
396     return 1 unless @$cnlist; # no attached volumes
397     return 0 if @$cnlist > 1; # multiple attached volumes
398     return 0 unless $$cnlist[0] == $vol_id; # attached volume is not the context vol.
399
400     # see if the sole remaining context volume has any attached copies
401     for my $cn (@$cnlist) {
402         my $copylist = $editor->search_asset_copy(
403             [
404                 { call_number => $cn, deleted => 'f' }, 
405                 { limit => 1 },
406             ], { idlist => 1 });
407         return 0 if @$copylist; # false if we find any copies
408     }
409
410     return 1;
411 }
412
413 # --------------------------------------------------------------------------
414 # returns true if the given title (id) has active hold requests on it
415 # --------------------------------------------------------------------------
416 sub title_has_holds {
417     my($class, $editor, $rid) = @_;
418
419     # check if $rid is an object, because may be passing the volume
420     # with a fleshed record in one of our callers.
421     $rid = $rid->id() if (ref($rid));
422
423     my $holds = $editor->search_action_hold_request(
424         [
425            { fulfillment_time  => undef,
426             cancel_time         => undef,
427             hold_type           => 'T',
428             target              => $rid },
429            { limit => 1 },
430         ], { idlist => 1 });
431     return 0 unless @$holds;
432
433     return 1; # we found a hold
434 }
435 1;