]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Record.pm
0e42be0055a5b1ee94e299af1d07da287b88cf07
[working/Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / WWW / EGCatLoader / Record.pm
1 package OpenILS::WWW::EGCatLoader;
2 use strict; use warnings;
3 use Apache2::Const -compile => qw(OK DECLINED FORBIDDEN HTTP_INTERNAL_SERVER_ERROR REDIRECT HTTP_BAD_REQUEST);
4 use OpenSRF::Utils::Logger qw/$logger/;
5 use OpenILS::Utils::CStoreEditor qw/:funcs/;
6 use OpenILS::Utils::Fieldmapper;
7 use OpenILS::Application::AppUtils;
8 use Net::HTTP::NB;
9 use IO::Select;
10 my $U = 'OpenILS::Application::AppUtils';
11
12 our $ac_types = ['toc',  'anotes', 'excerpt', 'summary', 'reviews'];
13
14 # context additions: 
15 #   record : bre object
16 sub load_record {
17     my $self = shift;
18     my %kwargs = @_;
19     my $ctx = $self->ctx;
20     $ctx->{page} = 'record';  
21
22     $self->timelog("load_record() began");
23
24     my $rec_id = $ctx->{page_args}->[0];
25
26     return Apache2::Const::HTTP_BAD_REQUEST 
27         unless $rec_id and $rec_id =~ /^\d+$/;
28
29     $self->added_content_stage1($rec_id);
30     $self->timelog("past added content stage 1");
31
32     my $org = $self->_get_search_lib();
33     my $org_name = $ctx->{get_aou}->($org)->shortname;
34     my $pref_ou = $self->_get_pref_lib();
35     my $depth = $self->cgi->param('depth');
36     $depth = $ctx->{get_aou}->($org)->ou_type->depth 
37         unless defined $depth; # can be 0
38
39     my $copy_depth = $self->cgi->param('copy_depth');
40     $copy_depth = $depth unless defined $copy_depth; # can be 0
41     $self->ctx->{copy_depth} = $copy_depth;
42
43     my $copy_limit = int($self->cgi->param('copy_limit') || 10);
44     my $copy_offset = int($self->cgi->param('copy_offset') || 0);
45
46     $self->get_staff_search_settings;
47     if ($ctx->{staff_saved_search_size}) {
48         $ctx->{saved_searches} = ($self->staff_load_searches)[1];
49     }
50     $self->timelog("past staff saved searches");
51
52     $self->fetch_related_search_info($rec_id) unless $kwargs{no_search};
53     $self->timelog("past related search info");
54
55     # Check for user and load lists and prefs
56     if ($self->ctx->{user}) {
57         $self->_load_lists_and_settings;
58         $self->timelog("load user lists and settings");
59     }
60
61     # run copy retrieval in parallel to bib retrieval
62     # XXX unapi
63     my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
64     $cstore->session_locale($OpenILS::Utils::CStoreEditor::default_locale);
65     my $copy_rec = $cstore->request(
66         'open-ils.cstore.json_query.atomic', 
67         $self->mk_copy_query($rec_id, $org, $copy_depth, $copy_limit, $copy_offset, $pref_ou)
68     );
69
70     # find foreign copy data
71     my $peer_rec = $U->simplereq(
72         'open-ils.search',
73         'open-ils.search.peer_bibs', $rec_id );
74
75     $ctx->{foreign_copies} = $peer_rec;
76
77     my (undef, @rec_data) = $self->get_records_and_facets([$rec_id], undef, {
78         flesh => '{holdings_xml,bmp,mra,acp,acnp,acns}',
79         site => $org_name,
80         depth => $depth,
81         pref_lib => $pref_ou
82     });
83
84     $self->timelog("past get_records_and_facets()");
85     $ctx->{bre_id} = $rec_data[0]->{id};
86     $ctx->{marc_xml} = $rec_data[0]->{marc_xml};
87
88     $ctx->{copies} = $copy_rec->gather(1);
89
90     # Add public copy notes to each copy - and while we're in there, grab peer bib records
91     foreach my $copy (@{$ctx->{copies}}) {
92         $copy->{notes} = $U->simplereq(
93             'open-ils.circ',
94             'open-ils.circ.copy_note.retrieve.all',
95             {itemid => $copy->{id}, pub => 1 }
96         );
97         $self->timelog("past copy note retrieval call");
98         $copy->{peer_bibs} = $U->simplereq(
99             'open-ils.search',
100             'open-ils.search.multi_home.bib_ids.by_barcode',
101             $copy->{barcode}
102         );
103         $self->timelog("past peer bib id retrieval");
104         my @peer_marc;
105         foreach my $bib (@{$copy->{peer_bibs}}) {
106             my (undef, @peer_data) = $self->get_records_and_facets(
107                 [$bib], undef, {
108                     flesh => '{holdings_xml,acp,acnp,acns,exclude_invisible_acn}',
109                     site => $org_name,
110                     depth => $depth,
111                     pref_lib => $pref_ou
112             });
113             #$copy->{peer_bib_marc} = $peer_data[0]->{marc_xml};
114             push @peer_marc, $peer_data[0]->{marc_xml};
115         }
116         $copy->{peer_bib_marc} = \@peer_marc;
117         $self->timelog("past peer bib record retrieval");
118     }
119
120     $self->timelog("past store copy retrieval call");
121     $ctx->{copy_limit} = $copy_limit;
122     $ctx->{copy_offset} = $copy_offset;
123
124     $ctx->{have_holdings_to_show} = 0;
125     $ctx->{have_mfhd_to_show} = 0;
126
127     $self->get_hold_copy_summary($rec_id, $org);
128
129     $self->timelog("past get_hold_copy_summary()");
130     $self->ctx->{bib_is_dead} = OpenILS::Application::AppUtils->is_true(
131         OpenILS::Utils::CStoreEditor->new->json_query({
132             select => { bre => [ 'deleted' ] },
133             from => 'bre',
134             where => { 'id' => $rec_id }
135         })->[0]->{deleted}
136     );
137
138     $cstore->kill_me;
139
140     if (
141         $ctx->{get_org_setting}->
142             ($org, "opac.fully_compressed_serial_holdings")
143     ) {
144         # We're loading this data here? Are we therefore assuming that we
145         # *are* going to display something in the "issues" expandy?
146         $self->load_serial_holding_summaries($rec_id, $org, $copy_depth);
147     } else {
148         $ctx->{mfhd_summaries} =
149             $self->get_mfhd_summaries($rec_id, $org, $copy_depth);
150
151         if ($ctx->{mfhd_summaries} && scalar(@{$ctx->{mfhd_summaries}})
152         ) {
153             $ctx->{have_mfhd_to_show} = 1;
154         };
155     }
156
157     $self->timelog("past serials holding stuff");
158
159     my %expandies = (
160         marchtml => sub {
161             $ctx->{marchtml} = $self->mk_marc_html($rec_id);
162         },
163         issues => sub {
164             return;
165             # XXX this needed?
166         },
167         cnbrowse => sub {
168             $self->prepare_browse_call_numbers();
169         }
170     );
171
172     my @expand = $self->cgi->param('expand');
173     if (grep {$_ eq 'all'} @expand) {
174         $ctx->{expand_all} = 1;
175         $expandies{$_}->() for keys %expandies;
176
177     } else {
178         for my $exp (@expand) {
179             $ctx->{"expand_$exp"} = 1;
180             $expandies{$exp}->() if exists $expandies{$exp};
181         }
182     }
183
184     $self->timelog("past expandies");
185
186     $self->added_content_stage2($rec_id);
187
188     $self->timelog("past added content stage 2");
189
190     return Apache2::Const::OK;
191 }
192
193 # collect IDs and info on the search that lead to this details page
194 # If no search query, etc is present, we leave ctx.search_result_index == -1
195 sub fetch_related_search_info {
196     my $self = shift;
197     my $rec_id = shift;
198     my $ctx = $self->ctx;
199     $ctx->{search_result_index} = -1;
200
201     $self->load_rresults(internal => 1);
202
203     my @search_ids = @{$ctx->{ids}};
204     return unless @search_ids;
205
206     for my $idx (0..$#search_ids) {
207         if ($search_ids[$idx] == $rec_id) {
208             $ctx->{prev_search_record} = $search_ids[$idx - 1] if $idx > 0;
209             $ctx->{next_search_record} = $search_ids[$idx + 1];
210             $ctx->{search_result_index} = $idx;
211             last;
212         }
213     }
214
215     $ctx->{first_search_record} = $search_ids[0];
216     $ctx->{last_search_record} = $search_ids[-1];
217 }
218
219
220 sub mk_copy_query {
221     my $self = shift;
222     my $rec_id = shift;
223     my $org = shift;
224     my $depth = shift;
225     my $copy_limit = shift;
226     my $copy_offset = shift;
227     my $pref_ou = shift;
228
229     my $query = $U->basic_opac_copy_query(
230         $rec_id, undef, undef, $copy_limit, $copy_offset, $self->ctx->{is_staff}
231     );
232
233     if($org != $self->ctx->{aou_tree}->()->id) { 
234         # no need to add the org join filter if we're not actually filtering
235         $query->{from}->{acp}->{aou} = {
236             fkey => 'circ_lib',
237             field => 'id',
238             filter => {
239                 id => {
240                     in => {
241                         select => {aou => [{
242                             column => 'id', 
243                             transform => 'actor.org_unit_descendants',
244                             result_field => 'id', 
245                             params => [$depth]
246                         }]},
247                         from => 'aou',
248                         where => {id => $org}
249                     }
250                 }
251             }
252         };
253     };
254
255     # Unsure if we want these in the shared function, leaving here for now
256     unshift(@{$query->{order_by}},
257         { class => "aou", field => 'id',
258           transform => 'evergreen.rank_ou', params => [$org, $pref_ou]
259         }
260     );
261     push(@{$query->{order_by}},
262         { class => "acp", field => 'status',
263           transform => 'evergreen.rank_cp_status'
264         }
265     );
266
267     return $query;
268 }
269
270 sub mk_marc_html {
271     my($self, $rec_id) = @_;
272
273     # could be optimized considerably by performing the xslt on the already fetched record
274     return $U->simplereq(
275         'open-ils.search', 
276         'open-ils.search.biblio.record.html', $rec_id, 1);
277 }
278
279 sub load_serial_holding_summaries {
280     my ($self, $rec_id, $org, $depth) = @_;
281
282     my $limit = $self->cgi->param("slimit") || 10;
283     my $offset = $self->cgi->param("soffset") || 0;
284
285     my $serial = create OpenSRF::AppSession("open-ils.serial");
286
287     # First, get the tree of /summaries/ of holdings.
288     my $tree = $serial->request(
289         "open-ils.serial.holding_summary_tree.by_bib",
290         $rec_id, $org, $depth, $limit, $offset
291     )->gather(1);
292
293     return if $self->apache_log_if_event(
294         $tree, "getting holding summary tree for record $rec_id"
295     );
296
297     # Next, if requested, get a list of individual holdings under a
298     # particular summary.
299     my $holdings;
300     my $summary_id = int($self->cgi->param("sid") || 0);
301     my $summary_type = $self->cgi->param("stype");
302
303     if ($summary_id and $summary_type) {
304         my $expand_path = [ $self->cgi->param("sepath") ],
305         my $expand_limit = $self->cgi->param("selimit");
306         my $expand_offsets = [ $self->cgi->param("seoffset") ];
307         my $auto_expand_first = 0;
308
309         if (not @$expand_offsets) {
310             $expand_offsets = undef;
311             $auto_expand_first = 1;
312         }
313
314         $holdings = $serial->request(
315             "open-ils.serial.holdings.grouped_by_summary",
316             $summary_type, $summary_id,
317             $expand_path, $expand_limit, $expand_offsets,
318             $auto_expand_first,
319             1 + ($self->ctx->{is_staff} ? 1 : 0)
320         )->gather(1);
321
322         if ($holdings and ref $holdings eq "ARRAY") {
323             $self->place_holdings_with_summary(
324                     $tree, $holdings, $summary_id, $summary_type
325             ) or $self->apache->log->warn(
326                 "could not place holdings within summary tree"
327             );
328         } else {
329             $self->apache_log_if_event(
330                 $holdings, "getting holdings grouped by summary $summary_id"
331             );
332         }
333     }
334
335     $serial->kill_me;
336
337     # The presence of any keys in the tree hash other than 'more' means that we
338     # must have /something/ we could show.
339     $self->ctx->{have_holdings_to_show} = grep { $_ ne 'more' } (keys %$tree);
340
341     $self->ctx->{holding_summary_tree} = $tree;
342 }
343
344 # This helper to load_serial_holding_summaries() recursively searches in
345 # $tree for a holding summary matching $sid and $stype, and places $holdings
346 # within the node for that summary. IOW, this is about showing expanded
347 # holdings under their "parent" summary.
348 sub place_holdings_with_summary {
349     my ($self, $tree, $holdings, $sid, $stype) = @_;
350
351     foreach my $sum (@{$tree->{holding_summaries}}) {
352         if ($sum->{id} == $sid and $sum->{summary_type} eq $stype) {
353             $sum->{holdings} = $holdings;
354             return 1;
355         }
356     }
357
358     foreach my $child (@{$tree->{children}}) {
359         return 1 if $self->place_holdings_with_summary(
360             $child, $holdings, $sid, $stype
361         );
362     }
363
364     return;
365 }
366
367 sub get_mfhd_summaries {
368     my ($self, $rec_id, $org, $depth) = @_;
369
370     my $serial = create OpenSRF::AppSession("open-ils.search");
371     my $result = $serial->request(
372         "open-ils.search.serial.record.bib.retrieve",
373         $rec_id, $org, $depth
374     )->gather(1);
375
376     $serial->kill_me;
377     return $result;
378 }
379
380 sub any_call_number_label {
381     my ($self) = @_;
382
383     if ($self->ctx->{copies} and @{$self->ctx->{copies}}) {
384         return $self->ctx->{copies}->[0]->{call_number_label};
385     } else {
386         return;
387     }
388 }
389
390 sub prepare_browse_call_numbers {
391     my ($self) = @_;
392
393     my $cn = ($self->cgi->param("cn") || $self->any_call_number_label) or
394         return [];
395
396     my $org_unit = $self->ctx->{get_aou}->($self->_get_search_lib()) ||
397         $self->ctx->{aou_tree}->();
398
399     my $supercat = create OpenSRF::AppSession("open-ils.supercat");
400     my $results = $supercat->request(
401         "open-ils.supercat.call_number.browse", 
402         $cn, $org_unit->shortname, 9, $self->cgi->param("cnoffset")
403     )->gather(1) || [];
404
405     $supercat->kill_me;
406
407     $self->ctx->{browsed_call_numbers} = [
408         map {
409             $_->record->marc(
410                 (new XML::LibXML)->parse_string($_->record->marc)
411             );
412             $_;
413         } @$results
414     ];
415     $self->ctx->{browsing_ou} = $org_unit;
416 }
417
418 sub get_hold_copy_summary {
419     my ($self, $rec_id, $org) = @_;
420     my $ctx = $self->ctx;
421     
422     my $search = OpenSRF::AppSession->create('open-ils.search');
423     my $copy_count_meth = 'open-ils.search.biblio.record.copy_count';
424     # We want to include OPAC-invisible copies in a staff context
425     if ($ctx->{is_staff}) {
426         $copy_count_meth .= '.staff';
427     }
428     my $req1 = $search->request($copy_count_meth, $org, $rec_id); 
429
430     # if org unit hiding applies, limit the hold count to holds
431     # whose pickup library is within our depth-scoped tree
432     my $count_args = {};
433     while ($org and $ctx->{org_within_hiding_scope}->($org)) {
434         $count_args->{pickup_lib_descendant} = $org;
435         $org = $ctx->{get_aou}->($org)->parent_ou;
436     }
437
438     $self->ctx->{record_hold_count} = $U->simplereq(
439         'open-ils.circ', 'open-ils.circ.bre.holds.count', 
440         $rec_id, $count_args);
441
442     $self->ctx->{copy_summary} = $req1->recv->content;
443
444     $search->kill_me;
445 }
446
447 sub load_print_record {
448     my $self = shift;
449
450     my $rec_id = $self->ctx->{page_args}->[0] 
451         or return Apache2::Const::HTTP_BAD_REQUEST;
452
453     $self->{ctx}->{bre_id} = $rec_id;
454     $self->{ctx}->{printable_record} = $U->simplereq(
455         'open-ils.search',
456         'open-ils.search.biblio.record.print', $rec_id);
457
458     return Apache2::Const::OK;
459 }
460
461 sub load_email_record {
462     my $self = shift;
463
464     my $rec_id = $self->ctx->{page_args}->[0] 
465         or return Apache2::Const::HTTP_BAD_REQUEST;
466
467     $self->{ctx}->{bre_id} = $rec_id;
468     $U->simplereq(
469         'open-ils.search',
470         'open-ils.search.biblio.record.email', 
471         $self->ctx->{authtoken}, $rec_id);
472
473     return Apache2::Const::OK;
474 }
475
476 # for each type, fire off the reqeust to see if content is available
477 # ctx.added_content.$type.status:
478 #   1 == available
479 #   2 == not available
480 #   3 == unknown
481 sub added_content_stage1 {
482     my $self = shift;
483     my $rec_id = shift;
484     my $ctx = $self->ctx;
485     my $sel_type = $self->cgi->param('ac') || '';
486     my $key = $self->get_ac_key($rec_id);
487     ($key = $key->{value}) =~ s/^\s+//g if $key;
488
489     # Connect to this machine's IP address, using the same 
490     # Host with which our caller used to connect to us.
491     # This avoids us having to route out of the cluster 
492     # and back in to reach the top-level virtualhost.
493     my $ac_addr = $ENV{SERVER_ADDR};
494     my $ac_host = $self->apache->hostname;
495     my $ac_failed = 0;
496
497     $logger->info("tpac: added content connecting to $ac_addr / $ac_host");
498
499     $ctx->{added_content} = {};
500     for my $type (@$ac_types) {
501         last if $ac_failed;
502         $ctx->{added_content}->{$type} = {content => ''};
503         $ctx->{added_content}->{$type}->{status} = $key ? 3 : 2;
504
505         if ($key) {
506             $logger->debug("tpac: starting added content request for $key => $type");
507
508             # Net::HTTP::NB is non-blocking /after/ the initial connect()
509             # Passing Timeout=>1 ensures we wait no longer than 1 second to 
510             # connect to the local Evergreen instance (i.e. ourself).  
511             # Connecting to oneself should either be very fast (normal) 
512             # or very slow (routing problems).
513
514             my $req = Net::HTTP::NB->new(Host => $ac_addr, Timeout => 1);
515             if (!$req) {
516                 $logger->warn("Unable to connect to $ac_addr / $ac_host".
517                     " for added content lookup for $key: $@");
518                 $ac_failed = 1;
519                 next;
520             }
521
522             $req->host($self->apache->hostname);
523
524             my $http_type = ($type eq $sel_type) ? 'GET' : 'HEAD';
525             $req->write_request($http_type => "/opac/extras/ac/$type/html/" . uri_escape_utf8($key));
526             $ctx->{added_content}->{$type}->{request} = $req;
527         }
528     }
529 }
530
531 # check each outstanding request.  If it's ready, read the HTTP 
532 # status and use it to determine if content is available.  Otherwise,
533 # leave the status as unknown.
534 sub added_content_stage2 {
535     my $self = shift;
536     my $ctx = $self->ctx;
537     my $sel_type = $self->cgi->param('ac') || '';
538
539     for my $type (keys %{$ctx->{added_content}}) {
540         my $content = $ctx->{added_content}->{$type};
541
542         if ($content->{status} == 3) {
543             $logger->debug("tpac: finishing added content request for $type");
544
545             my $req = $content->{request};
546             my $sel = IO::Select->new($req);
547
548             # if we are requesting a specific type of content, give the 
549             # backend code a little extra time to retrieve the content.
550             my $wait = $type eq $sel_type ? 3 : 0; # TODO: config?
551
552             if ($sel->can_read($wait)) {
553                 my ($code) = $req->read_response_headers;
554                 $content->{status} = $code eq '200' ? 1 : 2;
555                 $logger->debug("tpac: added content request for $type returned $code");
556
557                 if ($code eq '200' and $type eq $sel_type) {
558                     while (1) {
559                         my $buf;
560                         my $n = $req->read_entity_body($buf, 1024);
561                         last unless $n;
562                         $content->{content} .= $buf;
563                     }
564                 }
565             }
566         }
567         # To avoid a lot of hanging connections.
568         $content->{request}->shutdown(2) if ($content->{request});
569     }
570 }
571
572 # XXX this is copied directly from AddedContent.pm in 
573 # working/user/jeff/ac_by_record_id_rebase.  When Jeff's
574 # branch is merged and Evergreen gets added content 
575 # lookup by ID, this can be removed.
576 # returns [{tag => $tag, value => $value}, {tag => $tag2, value => $value2}]
577 sub get_ac_key {
578     my $self = shift;
579     my $rec_id = shift;
580     my $key_data = $self->editor->json_query({
581         select => {mfr => ['tag', 'value']},
582         from => 'mfr',
583         where => {
584             record => $rec_id,
585             '-or' => [
586                 {
587                     '-and' => [
588                         {tag => '020'},
589                         {subfield => 'a'}
590                     ]
591                 }, {
592                     '-and' => [
593                         {tag => '024'},
594                         {subfield => 'a'},
595                         {ind1 => 1}
596                     ]
597                 }
598             ]
599         }
600     });
601
602     return (
603         grep {$_->{tag} eq '020'} @$key_data,
604         grep {$_->{tag} eq '024'} @$key_data
605     )[0];
606 }
607
608 1;